Advertisement
Guest User

int_to_bin_str

a guest
Aug 30th, 2016
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.58 KB | None | 0 0
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <string.h>
  4.  
  5. char* to_bin_str(int num)
  6. {
  7.     char temp[2];
  8.     char bin_str[33] = {0};
  9.     int shifts = 31;
  10.     int bit;
  11.  
  12.     temp[1] = '\0';
  13.  
  14.     while(shifts >= 0)
  15.     {
  16.         bit = num & (1 << shifts);
  17.         shifts--;
  18.  
  19.         temp[0] = (bit != 0) + '0';
  20.         strcat(bin_str, temp);
  21.     }
  22.  
  23.     return strdup(bin_str);
  24. }
  25.  
  26. int main()
  27. {
  28.     int num = 0;
  29.     char* bin_str = NULL;
  30.  
  31.     scanf("%d", &num);
  32.  
  33.     bin_str = to_bin_str(num);
  34.     printf("%s\n", bin_str);
  35.  
  36.     free(bin_str);
  37.  
  38.     return 0;
  39. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement