Right way to show numbers in binary/hex/octal in your opinion?

rempas rempas at tutanota.com
Sat Dec 25 21:12:33 UTC 2021

So I have this function that converts a number to a string and it 
can return it in any base you want. However, for negative 
numbers, the result may not be what you expected for bases other 
than decimal if you have used "printf" or "wirtef". Let's say 
that we want to convert then number -10 from decimal to hex. 
There are two possible results (check 

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)

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....

Here are the advantages of these two methods in my humble opinion:

First method:
1. Is is what my function does and I would prefer not to change 
it obviously. Also implementing the other behavior, would need a 
lot of work (and of course I will have to figure it out, don't 
know how to do it) and it will make the function much slower.
2. It is easier on they eyes as it makes it more obvious to 
understand if the number is signed or not and so what the 
equivalent is in other systems.

Second method:
1. It is probably what people would expect and what makes 
scientifically more sense as decimal was supposed to be the only 
base that will make sense for humans to read hence be the only 
base that has the "-" character.

Anyway, I don't even know why it will be practical useful to 
print a number in another system so, what are your thoughts?

More information about the Digitalmars-d mailing list