Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- void intToBinary(int num, char* string)
- {
- string[32] = '\0';
- int i,j;
- int temp = num;
- // is num negative?
- int isNegative = num < 0 ? 1 : 0;
- //negate all bits and add 1 (two complements)
- if(isNegative)
- {
- temp = -1 * temp; //absolute value
- //In order to get the negative number in
- // 2's complement you can either negate and
- // increment, or decrement by 1 and negate.
- //In this function, temp gets negated after
- //the conversion to string
- --temp;
- }
- //Write binary of positive num to string
- for(i = 0, j = 31; i < 32; i++,j--)
- {
- if(pow(2,j) <= temp)
- {
- //Temp is decreased when the bit is 1
- temp = temp - pow(2, j);
- string[i] = '1';
- }
- else
- {
- //Nothing happens to temp when the bit is 0
- string[i] = '0';
- }
- }
- if(isNegative)
- {
- for(i = 0; i < 32; i++)
- {
- //negate bits
- string[i] = string[i] == '1' ? '0' : '1';
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement