Convert 4 little-endian chars to 1 int.

Nov 10, 2008 at 1:08pm
I want to convert 4 chars stored in little-endian format on a file to one integer. I do it this way:

 
n = c[0] + c[1] * 256 + c[2] * 65536 + c[3] * 16777216;


I'd like to do something like this:

1
2
3
4
5
n = (unsigned int) * c; // Get the bits and put them into an integer
n = 	(n >> 24) |			// Move first byte to the end,
	((n << 8) & 0x00FF0000) |	// move 2nd byte to 3rd,
	((n >> 8) & 0x0000FF00) |	// move 3rd byte to 2nd,
	(n << 24);			// move last byte to start. 


I'm using VC++ 2008, with the /J compiling directive (fill chars with 0's instead of 1's).

It doesn't seem to work. Any clue?
Nov 10, 2008 at 2:14pm
Works for me.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
#include <iostream>
#include <cstdlib>
#include <cassert>

using namespace std;

int main( int argc, char* argv[] ) {
   assert( argc > 1 );
   unsigned x = atoi( argv[1] );
   cout << hex << " x = " << x << endl;
   x = ( x >> 24 ) | ( ( x << 8 ) & 0x00FF0000 ) |
       ( ( x >> 8 ) & 0x0000FF00 ) | ( x << 24 );
   cout << " x = " << x << endl;
}


a.out 274847568
x = 1061d750
x = 50d76110

What does it do for you?
Nov 10, 2008 at 4:45pm
atoi() parses a string to convert it to a number. So, "1234" can be converted to the number 1234.

My problem is not the "Little-endian to Big-endian" converter: it's the "n = (unsigned int) * c;" statement. So:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

using namespace std;

int main(void)
{
	char sOffset [] = "Çüéâ"; // 2,206,368,128; little-endian notation; ASCII 128 129 130 131
	unsigned int nOffset = (unsigned int) * sOffset;
	nOffset =	(nOffset >> 24) |					// Move first byte to the end,
				((nOffset << 8) & 0x00FF0000) |	// move 2nd byte to 3rd,
				((nOffset >> 8) & 0x0000FF00) |	// move 3rd byte to 2nd,
				(nOffset << 24);					// move last byte to start.

	cout << sOffset << " :" << nOffset << endl;
}


Gives me this result:

╟ⁿΘΓ :3338665984

As you can see, even my string is wrong and I don't have any idea why... But you've got the idea of what I need.
Last edited on Nov 10, 2008 at 4:52pm
Nov 10, 2008 at 7:31pm
If sOffset is a char[], then *sOffset is a char.
So line #8 is reading only a single character from memory, not 4 bytes.

This is why 3338665984 == c7000000h

You need

 
unsigned int nOffset = *reinterpret_cast<unsigned*>( sOffset );

Nov 11, 2008 at 12:30pm
Awesome! Now I understand why we don't need the Little to Big-endian change: casting the unsigned int, the value comes automatically.

Thank you so much, JSmith!!!!
Topic archived. No new replies allowed.