Originally Posted by Mrzev
Oh god, i didnt even think of the bitwize math that you can do. Every time i made a calc program as an example for test driven development, i made functions like subtract(X,Y) by doing X-Y. I never even thought of even doing the bitwize style. My favorite bitnotation calculation is if you multiply any number by 2. Just add a 0 at the end =)
The following pseudocode doesn't handle unsigned or float numbers, but it overviews the basics (note: the negative numbers represent the 2's complement). Since it is going to be used on a per-byte basis, the loop can be sped up significantly by unrolling 8 times per loop (set the counter to the sizeof(input number type) instead of bit length).
If you don't want the 2's complement, take the 1's complement (NOT) and add 1 to get the positive version then add the neg sign.
Things are easy for unsigned. reduce the array size by one and do the same thing.
Adding support for float requires splitting the number into sign bit, exponent, and mantissa. Insert the sign, insert the exponent, insert the 'e', then insert the implied 1 and the mantissa. This gets harder when you support multiple float sizes as each uses different quantities of exponent and mantissa bits (this needs to be hard coded).
Edited by hajile - 3/7/14 at 4:51pm
//the extras are for string terminator and sign
char array[BIT_LENGTH + 2]
if leftmost bit is a 1:
array = '-'
array = '+'
//set a pointer (temp_ptr) to the end of the array (working right to left)
char *temp_ptr = array[last element];
//set final char to null then decrement
*temp_ptr-- = '\0';
//we're working backward (right to left) because it's more efficient
for (i = number of bits; i > 0; i--):
//shift the input integer eg. 10011011 --> 01001101
//then AND with 0000 0001
//we shift the input instead of the 1 because so we always get
//an answer of 0000 0000 or 0000 0001
//we then add 0011 0000 (0x30 in hex) to turn the 1 or 0 into the char equivalent
//finally, we decrement temp_ptr
*temp_ptr-- = ((in_number >>= 1) & 1) + 0x30;