2
votes

I'm probably very wrong here so please point out any misconceptions or mistakes I may have.

The input for this assignment is a string of some characters followed by a series of 4-byte unsigned integers in little-endian form. I read the input into an STL string, and used the substring function to isolate just the integers into a new string.

From what I understand, the least significant bits will be stored starting from the left most byte. An unsigned integer 131071(dec) whose binary representation is (0000 0000 0000 0001 1111 1111 1111 1111) would then be stored as 1111 1111 1111 1111 0000 0001 0000 0000

Parsing this new string 4 bytes at a time, I thought the first byte would contain the bits for values 0-255, 2nd byte for 256-65535 and so forth for the 3rd and 4th bytes.

I took the 1st byte, casted it to an unsigned int, and then shifted it 24 bits, I did the same to the 2nd and 3rd bytes, except 16 and 8 bit shifts respectively.

I got 255 and 65535 for the 1st and 2nd bytes as expected, but 0 for the 3rd byte. I believe I have to use the & operator somewhere, but I can't figure out where. If anyone could give me some advice, or perhaps a less foolish way of accomplishing the same task, I would greatly appreciate it.

1
I think we'd need to see some code to work out what has gone wrongjcoder
"leftmost byte" is somewhat ambiguous. In the manuals I've read about microarchitecture, the address always increases to the left. In other words the leftmost byte is the byte with the highest address. But I assume you take leftmost to mean "lowest address". (Normally I'm not pedantic about this, but left and right is a bit important when talking about endianness)Magnus Hoff
It would be stored as 1111 1111 1111 1111 0001 0000 0000 0000. Probably just a typo.Lundin

1 Answers

3
votes

If you got 0 for the 3rd byte, and your data matches your description, there's a bug in your code. The below code will correctly convert your sample data.

// Data from file
unsigned char Buffer[] = { 255, 255, 1, 0 };

// Convert the LSB data to an unsigned int
unsigned int Result = 0;
for (int i = 0; i < 4; ++i) {
  Result |= static_cast<unsigned int>(Buffer[i]) << (i*8);
}