Right way to show numbers in binary/hex/octal in your opinion?
Paul Backus
snarwin at gmail.com
Sat Dec 25 22:16:06 UTC 2021
On Saturday, 25 December 2021 at 21:12:33 UTC, rempas wrote:
> The first one is negate the number and convert it to hex and
> then add a "-" in front of the number. So the result will be:
> -a (which is what my function does)
This is the correct result.
> The second one is what "printf" and "writef" does which is
> using 2's complement. So in this case, we first convert the
> number to binary using 2's complement and then we convert this
> number to hex. In this example, `-10` to binary is
> `1111111111110110` which is `fff6` in hex. However, for some
> reason "printf" and "writef" return fffffff6 so go figure....
The two's complement representation of a number depends on the
width of the integer type you're using. For the number -10, the
16-bit two's complement is `fff6` and the 32-bit two's complement
is `fffffff6`.
The website you link to in your post uses 16 bit integers, but D
uses 32-bit `int`s by default. That's where the difference comes
from.
> Anyway, I don't even know why it will be practical useful to
> print a number in another system so, what are your thoughts?
If you implement the first method, users can still get the two's
complement representation very easily with (for example)
`cast(uint) -10`. On the other hand, if you implement the second
method, it's a lot trickier to get the non-two's-complement
result. So I think the first method is the better choice here.
More information about the Digitalmars-d
mailing list