Advertisement
lIlIlIlIIlI

Introduction_ToBitSting

Sep 9th, 2019
100
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 0.67 KB | None | 0 0
  1. #include<stdio.h>
  2. #include<stdlib.h>
  3.  
  4. char* toBitString(int n){
  5.     int end = 8 * sizeof(int);
  6.     char* bs = malloc( end * sizeof(char) + 1); // +1 是為了給 '\0'。
  7.     int i = 0, mask = 1; // 宣告mask。
  8. /*
  9.     while( i < end){
  10.         bs[end-i-1] = (n & 1) == 1? '1' : '0'; // 用1做&,從第1個做到第32個。
  11.         n = n>>1; // 所有字元往右移1。
  12.         i++;
  13.     }
  14. */
  15.     // 或是把1的遮罩改掉。
  16.     while( i < end){
  17.         bs[end-i-1] = (n & mask) == 0? '0' : '1'; // 用1做&,從第1個做到第32個。mask往左移 。
  18.         mask = mask<<1;
  19.         i++;
  20.     }
  21.  
  22.     bs[end] = '\0';
  23.     return bs;
  24.    
  25. }
  26.  
  27. int main(void){
  28.     int a = 10;
  29.     printf("%s\n", toBitString(a));
  30.     return 0;
  31. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement