# Convert bytes to int, keep the negative number

• 03-20-2009
umm
Convert bytes to int, keep the negative number
Hi,

I have written a function which read some bytes then convert it to int type
and I want it still keep the negative number, ex: 0xFFFF = -1

my sample code:
Code:

```FILE * fp; int value = 0; int read_num = 3; .... fread(&value, read_num, 1, fp);```
That is read 3 bytes, If it read 0xFFFFFF, the value is 16777215.
But I want get the negative number -1.

And, If read 2 (or 4 bytes), the 0xFFFF (or 0xFFFFFFFF) also need to convert to -1.

Thank you!!
• 03-20-2009
vart
so check the value of 16th bit (when you read 2 bytes) or 24th bit whenyou read 3 bytes

if this bit is 1 - fill the "unread bytes" with 0xFF if thats what you want

if you just want replace 0xFFFF with -1

Code:

`if(number == 0xFFFF) number = -1;`
is simplest way
• 03-20-2009
umm
Sorry I did not explain clear enough

If the first bit is 1 (0x8000~0xFFFF)
the value should be a negative number (-32768 ~ -1)

If the first bit is 0 (0x0000~0x7FFF)
the value should be a positive number (0 ~ 32767)

Thank you!!
• 03-20-2009
vart
Quote:

Originally Posted by umm
Sorry I did not explain clear enough

If the first bit is 1 (0x8000~0xFFFF)
the value should be a negative number (-32768 ~ -1)

If the first bit is 0 (0x0000~0x7FFF)
the value should be a positive number (0 ~ 32767)

Thank you!!

why not to read into short int and then assign to int?
• 03-20-2009
umm
Quote:

Originally Posted by vart
why not to read into short int and then assign to int?

Because I need read 1~4 Bytes in different case.
Thank you
• 03-20-2009
vart
Quote:

Originally Posted by umm
Because I need read 1~4 Bytes in different case.
Thank you

Then try to implement the algorithm I have suggested earlier
• 03-20-2009
umm
Quote:

Originally Posted by vart
Then try to implement the algorithm I have suggested earlier

Thank you so much!!
• 03-20-2009
nonoob
Basically vart's method:
Code:

```        if (((char *)&value)[read_num - 1] & 128)                 for (i = read_num; i < sizeof(value); i++)                         ((char *)&value)[i] = 255;```
Works for read_num being 1, 2, 3, or 4 bytes... or even higher if whatever data type is value might be 64-bit integer. Algorithm sizes to fit.