使用C在二进制表示中打印int

我正在寻找一个允许我打印int的二进制表示的函数。 到目前为止我所拥有的是什么;

char *int2bin(int a) { char *str,*tmp; int cnt = 31; str = (char *) malloc(33); /*32 + 1 , because its a 32 bit bin number*/ tmp = str; while ( cnt > -1 ){ str[cnt]= '0'; cnt --; } cnt = 31; while (a > 0){ if (a%2==1){ str[cnt] = '1'; } cnt--; a = a/2 ; } return tmp; } 

但是当我打电话时

 printf("a %s",int2bin(aMask)) // aMask = 0xFF000000 

我输出像;

0000000000000000000000000000000000xtpYy(还有一堆未知字符。

这是函数中的缺陷还是我打印字符数组的地址或什么? 对不起,我只是看不出我出错的地方。

NB代码来自这里

编辑:这不是家庭作业FYI,我正在尝试用不熟悉的语言调试别人的图像处理程序。 然而,如果它被标记为家庭作业,因为它是一个基本概念,然后公平竞争。

这是另一个在传递分配的缓冲区时更加优化的选项。 确保它的大小正确。

 // buffer must have length >= sizeof(int) + 1 // Write to the buffer backwards so that the binary representation // is in the correct order ie the LSB is on the far right // instead of the far left of the printed string char *int2bin(int a, char *buffer, int buf_size) { buffer += (buf_size - 1); for (int i = 31; i >= 0; i--) { *buffer-- = (a & 1) + '0'; a >>= 1; } return buffer; } #define BUF_SIZE 33 int main() { char buffer[BUF_SIZE]; buffer[BUF_SIZE - 1] = '\0'; int2bin(0xFF000000, buffer, BUF_SIZE - 1); printf("a = %s", buffer); } 

一些建议:

  • null-terminate你的字符串
  • 不要使用魔术数字
  • 检查malloc()的返回值
  • 不要malloc()的返回值
  • 因为您对二进制表示感兴趣,所以使用二进制运算而不是算术运算
  • 没有必要循环两次

这是代码:

 #include  #include  char * int2bin(int i) { size_t bits = sizeof(int) * CHAR_BIT; char * str = malloc(bits + 1); if(!str) return NULL; str[bits] = 0; // type punning because signed shift is implementation-defined unsigned u = *(unsigned *)&i; for(; bits--; u >>= 1) str[bits] = u & 1 ? '1' : '0'; return str; } 

您的字符串不是以空值终止的。 确保在字符串的末尾添加'\0'字符; 或者,您可以使用calloc而不是malloc来分配它,这将使返回给您的内存归零。

顺便说一下,这段代码还有其他问题:

  • 使用时,它会在您调用时分配内存,让调用者负责free()分配的字符串。 如果你只是在printf调用中调用它,你将泄漏内存。
  • 它对数字进行了两次传递,这是不必要的。 你可以在一个循环中完成所有事情。

这是您可以使用的替代实现。

 #include  #include  char *int2bin(unsigned n, char *buf) { #define BITS (sizeof(n) * CHAR_BIT) static char static_buf[BITS + 1]; int i; if (buf == NULL) buf = static_buf; for (i = BITS - 1; i >= 0; --i) { buf[i] = (n & 1) ? '1' : '0'; n >>= 1; } buf[BITS] = '\0'; return buf; #undef BITS } 

用法:

 printf("%s\n", int2bin(0xFF00000000, NULL)); 

第二个参数是指向要存储结果字符串的缓冲区的指针。如果没有缓冲区,则可以传递NULLint2bin将写入static缓冲区并将其返回给您。 这比原始实现的优点是调用者不必担心free()返回返回的字符串。

缺点是只有一个静态缓冲区,因此后续调用将覆盖先前调用的结果。 您无法保存多个调用的结果以供以后使用。 此外,它不是线程安全的,这意味着如果你从不同的线程调用这个函数,它们可能会破坏彼此的字符串。 如果有可能你需要传入自己的缓冲区而不是传递NULL ,如下所示:

 char str[33]; int2bin(0xDEADBEEF, str); puts(str); 

这是一个简单的算法。

 void decimalToBinary (int num) { //Initialize mask unsigned int mask = 0x80000000; size_t bits = sizeof(num) * CHAR_BIT; for (int count = 0 ;count < bits; count++) { //print (mask & num ) ? cout <<"1" : cout <<"0"; //shift one to the right mask = mask >> 1; } } 

这就是我所做的将一个interger显示为binairy代码,每4位分隔一次:

 int getal = 32; /** To determain the value of a bit 2^i , intergers are 32bits long**/ int binairy[getal]; /** A interger array to put the bits in **/ int i; /** Used in the for loop **/ for(i = 0; i < 32; i++) { binairy[i] = (integer >> (getal - i) - 1) & 1; } int a , counter = 0; for(a = 0;a<32;a++) { if (counter == 4) { counter = 0; printf(" "); } printf("%i", binairy[a]); teller++; } 

它可能有点大,但我总是以某种方式(我希望)每个人都能理解正在发生的事情。 希望这有帮助。

 #include //#include // use this if you are running your code in visual c++, linux don't // have this library. i have used it for getch() to hold the screen for input char. void showbits(int); int main() { int no; printf("\nEnter number to convert in binary\n"); scanf("%d",&no); showbits(no); // getch(); // used to hold screen... // keep code as it is if using gcc. if using windows uncomment #include & getch() return 0; } void showbits(int n) { int i,k,andmask; for(i=15;i>=0;i--) { andmask = 1 << i; k = n & andmask; k == 0 ? printf("0") : printf("1"); } } 

两件事情:

  1. 你把NUL角色放在哪里? 我看不到设置'\0'的地方。
  2. Int已签名,0xFF000000将被解释为负值。 因此, while (a > 0)将立即为假。

旁白:里面的malloc函数很难看。 怎样为int2bin提供缓冲区?

有几件事:

 int f = 32; int i = 1; do{ str[--f] = i^a?'1':'0'; }while(i<<1); 
  • 它是高度依赖平台的,但也许这个想法可以让你开始。
  • 为什么不使用memset(str,0,33)将整个char数组设置为0?
  • 别忘了免费()!!! 函数调用后的char *数组!

这里编写了两个简单版本(通过温和的重新格式化再现)。

 #include  /* Print n as a binary number */ void printbitssimple(int n) { unsigned int i; i = 1<<(sizeof(n) * 8 - 1); while (i > 0) { if (n & i) printf("1"); else printf("0"); i >>= 1; } } /* Print n as a binary number */ void printbits(int n) { unsigned int i, step; if (0 == n) /* For simplicity's sake, I treat 0 as a special case*/ { printf("0000"); return; } i = 1<<(sizeof(n) * 8 - 1); step = -1; /* Only print the relevant digits */ step >>= 4; /* In groups of 4 */ while (step >= n) { i >>= 4; step >>= 4; } /* At this point, i is the smallest power of two larger or equal to n */ while (i > 0) { if (n & i) printf("1"); else printf("0"); i >>= 1; } } int main(int argc, char *argv[]) { int i; for (i = 0; i < 32; ++i) { printf("%d = ", i); //printbitssimple(i); printbits(i); printf("\n"); } return 0; } 

包括

int main(void){

 int a,i,k=1; int arr[32]; \\ taken an array of size 32 for(i=0;i <32;i++) { arr[i] = 0; \\initialised array elements to zero } printf("enter a number\n"); scanf("%d",&a); \\get input from the user for(i = 0;i < 32 ;i++) { if(a&k) \\bit wise and operation { arr[i]=1; } else { arr[i]=0; } k = k<<1; \\left shift by one place evry time } for(i = 31 ;i >= 0;i--) { printf("%d",arr[i]); \\print the array in reverse } return 0; 

}

//当我们的老师要求我们这样做时,这就是我所做的

 int main (int argc, char *argv[]) { int number, i, size, mask; // our input,the counter,sizeofint,out mask size = sizeof(int); mask = 1<<(size*8-1); printf("Enter integer: "); scanf("%d", &number); printf("Integer is :\t%d 0x%X\n", number, number); printf("Bin format :\t"); for(i=0 ; i 

对我来说这是最简单的方法(对于8位表示):

 #include  #include  #include  char *intToBinary(int z, int bit_length){ int div; int counter = 0; int counter_length = (int)pow(2, bit_length); char *bin_str = calloc(bit_length, sizeof(char)); for (int i=counter_length; i > 1; i=i/2, counter++) { div = z % i; div = div / (i / 2); sprintf(&bin_str[counter], "%i", div); } return bin_str; } int main(int argc, const char * argv[]) { for (int i = 0; i < 256; i++) { printf("%s\n", intToBinary(i, 8)); //8bit but you could do 16 bit as well } return 0; } 

这是另一个不需要char *的解决方案。

 #include  #include  void print_int(int i) { int j = -1; while (++j < 32) putchar(i & (1 << j) ? '1' : '0'); putchar('\n'); } int main(void) { int i = -1; while (i < 6) print_int(i++); return (0); } 

或者这里是为了更加可读:

 #define GRN "\x1B[32;1m" #define NRM "\x1B[0m" void print_int(int i) { int j = -1; while (++j < 32) { if (i & (1 << j)) printf(GRN "1"); else printf(NRM "0"); } putchar('\n'); } 

这是输出:

 11111111111111111111111111111111 00000000000000000000000000000000 10000000000000000000000000000000 01000000000000000000000000000000 11000000000000000000000000000000 00100000000000000000000000000000 10100000000000000000000000000000 
 #include  #define BITS_SIZE 8 void int2Bin ( int a ) { int i = BITS_SIZE - 1; /* * Tests each bit and prints; starts with * the MSB */ for ( i; i >= 0; i-- ) { ( a & 1 << i ) ? printf ( "1" ) : printf ( "0" ); } return; } int main () { int d = 5; printf ( "Decinal: %d\n", d ); printf ( "Binary: " ); int2Bin ( d ); printf ( "\n" ); return 0; } 

不是那么优雅,但实现了你的目标,这很容易理解:

 #include int binario(int x, int bits) { int matriz[bits]; int resto=0,i=0; float rest =0.0 ; for(int i=0;i<8;i++) { resto = x/2; rest = x%2; x = resto; if (rest>0) { matriz[i]=1; } else matriz[i]=0; } for(int j=bits-1;j>=0;j--) { printf("%d",matriz[j]); } printf("\n"); } int main() { int num,bits; bits = 8; for (int i = 0; i < 256; i++) { num = binario(i,bits); } return 0; } 

这是我的解决方案。 它创建一个掩码,从所有0开始,最左边的位为1,并在假定的 32位整数中为每个位逻辑移位。 通过将当前屏蔽的整数的值转换为布尔值来顺序打印这些位。

 void printBits(int val){ for(unsigned int mask = 0x80000000; mask; mask >>= 1){ printf("%d", !!(mask & val)); } } 
 void print_binary(int n) { if (n == 0 || n ==1) cout << n; else { print_binary(n >> 1); cout << (n & 0x1); } }