Writing an 32 bit interger to 32 bit value in Binary

closed account (N36fSL3A)
(Rewritten:)

So, I was reading that article on binary files:

Disch wrote:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
u16 ReadU16(istream& file)
{
  u16 val;
  u8 bytes[2];

  file.read( (char*)bytes, 2 );  // read 2 bytes from the file
  val = bytes[0] | (bytes[1] << 8);  // construct the 16-bit value from those bytes

  return val;
}

void WriteU16(ostream& file, u16 val)
{
  u8 bytes[2];

  // extract the individual bytes from our value
  bytes[0] = (val) & 0xFF;  // low byte
  bytes[1] = (val >> 8) & 0xFF;  // high byte

  // write those bytes to the file
  file.write( (char*)bytes, 2 );
}




u32 would be the same way, but you would break it down and reconstruct it in 4 bytes rather than 2.


But, I don't know what he means by the part in bold text. It'd be nice if you guys could give me a snippet on what he meant.
Last edited on by Fredbill30
In the code he deals with short integers ( 16-bits) and says that in fact the same idea can be apllied to 32-bit integers.
Probably something like this (untested)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
u32 ReadU32(istream& file)
{
  u32 val;
  u8 bytes[4];

  file.read( (char*)bytes, 4 );  // read 2 bytes from the file
  val = bytes[0] | (bytes[1] << 8) | (byte[2] << 16) | (byte[3] << 24);  // construct the 32-bit value from those bytes

  return val;
}

void WriteU32(ostream& file, u32 val)
{
  u8 bytes[4];

  // extract the individual bytes from our value
  bytes[0] = (val) & 0xFF;//0xFFFF;  // low byte
  bytes[1] = (val >> 8) & 0xFF;//0xFFFF;
  bytes[2] = (val >> 16) & 0xFF;//0xFFFF; 
  bytes[3] = (val >> 24) & 0xFF;//0xFFFF;  // high byte

  // write those bytes to the file
  file.write( (char*)bytes, 4 );
}
Last edited on
closed account (N36fSL3A)
Can Disch confirm what's above?
naraku is correct, that is what I had in mind.

Though you should probably do & 0xFF instead of & 0xFFFF, since the goal is to isolate the byte, not the word.
closed account (N36fSL3A)
Alright thanks, this is solved.
Disch wrote:
Though you should probably do & 0xFF instead of & 0xFFFF, since the goal is to isolate the byte, not the word.
What the hell was I thinking, fixed.
closed account (N36fSL3A)
Wait, does this work with integers? Because it has a char pointer.
Yes, it works with integers.
Topic archived. No new replies allowed.