Converting chars to ints from binary file

I have kind of a complicated problem. I'm reading a binary file with open() and read(), and I would like to convert what's read into 32-bit integers. So basically, if I have a file with the following hex bytes: 0x12 0x34 0x56 0x78 0x9a 0xbc 0xde 0xfa

would give an array with the following ints:
0x78563412
0xFADEBC9A

(assuming little-endian)

and I can get this result with the following code:
1
2
3
int temp;
file.read((char*)&temp, sizeof(temp))
//push temp onto a vector, and repeat 


But this only works if there is a multiple of four bytes. If there were, say, these bytes in the file: 0x12 0x34 0x56 0x78 0x9a 0xbc 0xde 0xfa 0xf1 0xf2 0xf3
it gives this:
0x78563412
0xFADEBC9A
0xFAF3F2F1

when I want it to give this:
0x78563412
0xFADEBC9A
0x00F3F2F1

I've tried messing around with a number of strategies, but none seem to work. Reading only 3 bytes into the integer gives this same result, trying to read 4 just doesn't do anything at all. I've messed around trying to convert a char[4] array into an integer, but I haven't found anything. Can anyone help?


What about bitshifting?
Reading 4 characters (8bits) and shift them to there correct position inside the integer.

like
1
2
3
4
5
6
7
8
9
10
11
char c1=0;
char c2=0;
char c3=0;
char c4=0;
int result;
// try to read all 4chars. If it's not possible because it's end of file they are still 0
...
// put all 4 chars into the integer
result = (int)c4 + ((int)c3 << 8) + ((int)c2<<16) + ((int)c1<<24);
// for other type of bitorder
result = (int)c1 + ((int)c2 << 8) + ((int)c3<<16) + ((int)c4<<24);
Last edited on
Thanks for the suggestion! That seems to be workable, but I'm still having problems. If I use the following code:
1
2
int test = ((int)four[1] << 8);
printf("%X+%X=%X\n",(int)four[0],(int)test,(int)four[0]+test);


where four[0] = 0xf1, and four[1]=0xf2 (the rest don't matter for this example). I get this output:
FFFFFFF1+FFFFF200=FFFFF1F1

1. Why is it FFFFFFF1 and not 000000F1?
2. I'm assuming the answer to the first question will explain the second obvious problem, which is that the answer is not what I need it to be
The problem is the sign.
if four is an array of char, four[0] = 0xf1 means four[0] = -15 and int test = ((int)four[1] << 8); means test = -14 * (2^8).

So you add (-15) + (-3584) which makes -3599.
if four is an array of unsiged char it shoud work.
Last edited on
There we go, that works beautifully. Thank you so much Maik
Topic archived. No new replies allowed.