Advertisement
Guest User

Integer to binary char array

a guest
Sep 8th, 2015
215
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.12 KB | None | 0 0
  1. void intToBinary(int num, char* string)
  2. {
  3.     string[32] = '\0';
  4.     int i,j;
  5.     int temp = num;
  6.  
  7.     // is num negative?
  8.     int isNegative = num < 0 ? 1 : 0;
  9.  
  10.     //negate all bits and add 1 (two complements)
  11.     if(isNegative)
  12.     {
  13.         temp = -1 * temp; //absolute value
  14.        
  15.         //In order to get the negative number in
  16.         // 2's complement you can either negate and
  17.         // increment, or decrement by 1 and negate.
  18.         //In this function, temp gets negated after
  19.         //the conversion to string
  20.         --temp;
  21.     }
  22.  
  23.     //Write binary of positive num to string
  24.     for(i = 0, j = 31; i < 32; i++,j--)
  25.     {
  26.         if(pow(2,j) <= temp)
  27.         {
  28.            //Temp is decreased when the bit is 1
  29.            temp = temp - pow(2, j);
  30.            string[i] = '1';
  31.         }
  32.         else
  33.         {
  34.             //Nothing happens to temp when the bit is 0
  35.             string[i] = '0';
  36.         }
  37.     }
  38.  
  39.     if(isNegative)
  40.     {
  41.         for(i = 0; i < 32; i++)
  42.         {
  43.             //negate bits
  44.             string[i] = string[i] == '1' ? '0' : '1';
  45.         }
  46.     }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement