Reading 2 bytes from a file

hi there,

i've an issue with reading 2 bytes from a file. This 2 bytes are number, and i'd like to save it in int. The first byte from the file is unimportant.

1
2
3
4
5
int size = 0;
//...

s.get();
s.read(reinterpret_cast<char*>(&size), 2); 


Unfortunately, this code doesn't work. I get number 2304 instead of 9...

Do u know why is that ?
The file is in a system endianness other than the system you're on.

Probably, you are on a little endian system, and the value is stored big endian.

09 00 <- 9 in "little endian"
00 09 <- 9 in "big endian"


Because the endian is mixed up, you're reading the variable as 0x0900 instead of 0x0009 (0x0900 == 2304).

One solution is to read the bytes one at a time, and shift them appropriately:

1
2
3
4
5
6
7
8
unsigned char lo;
unsigned char hi;

// assuming the file stores them "big endian"
s.read(reinterpret_cast<char*>(&hi), 1);
s.read(reinterpret_cast<char*>(&lo), 1);

int size = (hi << 8) | lo;
http://www.cplusplus.com/forum/beginner/31584/#msg171056
I presume that you have opened the file with the ios::binary flag.
:-)
Thx very much !

But I can't figure it out how can I do sth opposite - reverse bits in the 'size' variable ?
I presume that you have opened the file with the ios::binary flag.


I had to.
But I can't figure it out how can I do sth opposite - reverse bits in the 'size' variable ?

You don't need to reverse bits, really. You just have to swap the bytes around.

But really, if you read the bytes in the right order, it's very simple:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
unsigned char lo;
unsigned char hi;

if( the_file_uses_big_endian )
{
    s.read(reinterpret_cast<char*>(&hi), 1);  // read high byte first
    s.read(reinterpret_cast<char*>(&lo), 1);
}
else if( the_file_uses_little_endian )
{
    s.read(reinterpret_cast<char*>(&lo), 1);  // read low byte first
    s.read(reinterpret_cast<char*>(&hi), 1);
}

// either way, you build 'size' the same way:
int size = (hi << 8) | lo;
But now I have to write this variable to a file :) write function writes 9 as 2304 so I need to split this variable into 2 4-bits parts - but I dont know how to do that...
Well, you need to google around bit-shifting and bit-masking in C and/or C++ and take a closer look at the examples and links given you. Good luck now!
Topic archived. No new replies allowed.