Does this process change if the binary is signed, or do we convert the string into hexadecimal using the same method?
Taking the unsigned binary value 1111 0110, when converting it into hexadecimal, we get the value F6. To convert back, we simply take each hex digit and convert it into its binary value. So F (which is decimal 15) is 1111, and 6 is 0110.
If the string "1111 0110" were signed, would the value of this string still be F6?
Usually when converting to hex, we just care about the bit-pattern, not the value represented by a 2's complement interpretation of those bits. By convention, readers expect that hex or binary is for bit-patterns rather than values, like a hex-dump of what's actually there rather than some meaning for the bits.
So yes, 1111 0110 is 0xF6. Both are ways to express the bit-pattern for an 8-bit 2's complement representation of -10, or for unsigned 246.
But you could print it as -0xa (signed base 16) just like you could print it as -10 (signed base 10) for an 8-bit 2's complement interpretation.
To implement this, you'd do if (val<0) { *buf++ = '-'; val = 0U - val; } at the start then carry on to convert the unsigned absolute value (magnitude) of the number into the rest of your output buffer, like for base 10.
(Except this is hex so we can get the leading digits first, by shifting or rotating. How to convert a binary integer number to a hex string?. Unless we want to skip leading zeros then it would be more convenient to start with the lowest 4-bit group and convert backwards into a buffer. In that case, just remember the original input and Tack on a - to the front after shifting out all the non-zero bits if the original input had been negative.)
A zero is positive
The usual technical terminology is that a zero is "non-negative", but also not positive. For two's complement bit-patterns, the MSB tells you whether it's negative or non-negative.
In assembly on machines with a flags register, most have a flag that's set according to the MSB, usually called the sign flag. It tells you whether the number was negative or not. To see if a number was positive, you also need the zero flag to be cleared, like x86 jg jumps if SF=OF && ZF=0. In a compare against zero like test al,al, the signed Overflow flag will be zero. https://www.felixcloutier.com/x86/jcc
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With