Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Using Hexadecimal numbers for array dimensioning and printing -what am I doing wrong?
#2
Yes that is expected behavior and becomes clear when you look at it in binary:

E800 = 1110 1000 0000 0000

So as you see the leftmost bit, which is the sign bit, is set here, which makes E800 as is into a negative integer number. Now when you assign it to a long variable, then the compiler tries to preserve the negative nature of that number and makes it into:

FFFFE800 = 1111 1111 1111 1111 1110 1000 0000 0000

rather than:

0000E800 = 0000 0000 0000 0000 1110 1000 0000 0000

as you'd expect it.

You must use the ~% suffix to explicitly tell the compiler that your given integer E800 shall be a unsigned number. By the way, you might think that writing the entire long value 0000E800 instead, i.e. including the leading zeros could fix the problem, but it does not as almost all compilers I know usually ignore leading zeros before any numbers, hence even 0000E800 would need either need the ~% or ~& suffix.



The whole thing only happens for numbers which have the sign bit set, i.e. 0000-7FFF should just work fine, while 8000-FFFF naturally are negative numbers and require the unsigned integer suffix.

The same thing would happen again at the long to integer64 boundary, i.e. when writing a long hex value but assigning it to a integer64 variable, then 00000000-7FFFFFFF would be ok as is, while 80000000-FFFFFFFF would need the unsigned long (~&) suffix to make the values unsigned.

There's no way around, that's simply how the binary system works.
Reply


Messages In This Thread
RE: Using Hexadecimal numbers for array dimensioning and printing -what am I doing wrong? - by RhoSigma - 08-13-2024, 11:22 AM



Users browsing this thread: 1 Guest(s)