简体   繁体   中英

Binary converting hex from unsigned char to int

I might be asking a duplicate question but can't seem to find it.

How do I convert a hex say from 1e in an unsigned char to 0x1e in an int ( not unsigned )?

and to concatenate them i would need to

hex3 = (hex1 << 8) | hex2;

and if i wanted to do it over and over again could i do this?

hex3 = (hex3 << 8) | hex2;

sorry these might be really questions but i cant seem to get my head round binary operations :(

edit: so.. can i do this?

int hex;
while (!feof(in))
{ 
   unsigned char input = fgetc(in);
  hex = hex + input;
};`

if the input was 1e will the hex be 0x1e and I later want to concatenate so if the next input was ff i would wan the output to be 0x1eff

Some notes

  1. You need to check the return value from fgetc to determine when the end-of-file has been reached. See while-feof-file-is-always-wrong .
  2. fgetc returns an int not a char . The reason is so that you can detect when EOF is returned.
  3. You can only shift bytes into the int until the int is full. On a 32-bit system, an int is only 4 bytes, so you can only do this 4 times.
  4. C doesn't have hex numbers and decimal numbers, it just has an int type that stores a number. The printf function can be used to display an int in hex or decimal. To display a number in decimal use printf("%d",n) , to display a number in hex use printf("%x",n) .

With that in mind, here's how I would write the code. (I'm assuming that an int is 4 bytes and the file has 4 or fewer bytes in it.)

int number = 0;
int c;
while ( (c = fgetc(in)) != EOF )
    number = (number << 8) | (c & 0xff);

printf( "%x\n", number );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM