-3

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

ObnoxiousFrog
  • 23
  • 1
  • 6
  • `unsigned char` is an integer type, just shorter (probably) than an int. You can just assign an unsigned char to an int. There is no problem unless `char` and `int` happen to be the same size and the value in the `char` is greater than `MAX_INT`; in practical terms, that will never happen. – rici Nov 14 '15 at 22:50
  • So basically i can do this? `unsigned char = hex, int hex1 = hex` – ObnoxiousFrog Nov 14 '15 at 22:51
  • It would help if you put together an [MCVE](http://stackoverflow.com/help/mcve). It's not entirely clear what `hex1` and `hex2` represent. – user3386109 Nov 14 '15 at 22:54

1 Answers1

0

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 );
Community
  • 1
  • 1
user3386109
  • 34,287
  • 7
  • 49
  • 68