0

So I'm currently learning about little endian, big endian, hex and binary. At the moment I have this array of bytes, represented in hex new byte[] { 0x06, 0x1B, 0x0A, 0xFF }; and if I try to get the int value, by reading it using little endian

int theValue = BitConverter.ToInt32(arr.Reverse().ToArray(), 0);

it gives me the correct value which is 102,435,583

however.. if I remove .Reverse().ToArray() aka read it as big endian, it gives me a negative value, since technically it exceeds the maximum value of an integer. The value I'm trying to get is 4,283,488,352.. I figured I would be able to just cast it as a uint by doing so uint theValue = (uint)BitConverter.ToInt32(arr, 0); I get this value 4,278,852,358 which as you can see is not correct.. It's close but not correct, and I've been told that this is because something overflows but I'm not sure what that means.

Why am I not getting the value 4,283,488,352 but rather a different (wrong) value 4,278,852,358

Riley Varga
  • 670
  • 1
  • 5
  • 15
  • Try `BitConverter.ToUInt32()`. The fourth byte (0xFF) has the high-order bit on, which causes the signed integer to go negative. `ToUInt32()` will produce an unsigned integer. – glenebob Mar 06 '21 at 17:49
  • That worked! Could you please elaborate a bit more in detail to why this is? I'm not sure how to interpret `The fourth byte (0xFF) has the high-order bit on` – Riley Varga Mar 06 '21 at 17:55
  • Does this answer your question? [What is “2's Complement”?](https://stackoverflow.com/questions/1049722/what-is-2s-complement) – Charlieface Mar 06 '21 at 19:26

0 Answers0