Number made of 4 chars with hex

谁说胖子不能爱 提交于 2020-01-06 15:29:25

问题


Iam programming in C++ and Iam comming with another "stupid" problem. If I have 4 chars like these:

char a = 0x90
char b = 0x01
char c = 0x00
char d = 0x00

when that all means hexadecimal number 0x00000190 which is 400 decimal number. How do I convert these chars to one int? I know i can do

int number = a;

but this will convert only one char to int. Could anybody help please?


回答1:


You may use:

int number = (a & 0xFF)
           | ((b & 0xFF) << 8) 
           | ((c & 0xFF) << 16)
           | ((d & 0xFF) << 24);

It would be simpler with unsigned values.




回答2:


like this

int number = ((d & 0xff) << 24) | ((c &0xff) << 16) | ((b & 0xff) << 8) | (a & 0xff);

the << is the bit shift operator and the & 0xff is necessary to avoid negative values when promoting char to int in the expression (totally right by Jarod42)




回答3:


This works:

unsigned char ua = a;
unsigned char ub = b;
unsigned char uc = c;
unsigned char ud = d;

unsigned long x = ua + ub * 0x100ul + uc * 0x10000ul + ud * 0x1000000ul

It is like place-value arithmetic in decimal but you are using base 0x100 instead of base 10.

If you are doing this a lot you could wrap it up in an inline function or a macro.


Note - the other answers posted so far using bitwise operations on (char)0x90 are all wrong for systems where plain char is signed, as they are forgetting that (char)0x90 is a negative value there, so after the integral promotions are applied, there are a whole lot of 1 bits on the left.



来源:https://stackoverflow.com/questions/28224041/number-made-of-4-chars-with-hex

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!