如何创建一个从整数打印二进制但具有一定位数的函数。
例如printBin(13,7)
会显示
0001101
#include<stdio.h>
#include<conio.h>
//Display integer number into binary using bitwise operator
void printBin(int num, int bits)
{
int mask = 0x4000;
if ((num & 0x8000) == 0)
printf("0");
else
printf("1");
while (mask != 0)
{
if ((num & mask) == 0)
printf("0");
else
printf("1");
mask = mask >> 1;
}
}
void main()
{
int intNum;
int intBits;
printf("\nEnter a integer number and number of bits :");
scanf("%d %d", &intNum, &intBits);
printf("\nInteger number in binary format :");
printBin(intNum, intBits);
getch();
}
答案 0 :(得分:0)
你正在大大过度复杂化。如果我理解你想要做什么(我没有阅读你的代码,因为格式化是一团糟),它就像迭代你想要打印的位一样简单,并打印每一位。因为从最高索引位开始,所以运行从最大索引到0的for循环。
您的功能可以是三行:
void printBin(int num, int bits) {
for (int i = bits-1; i >= 0; --i) {
printf("%d",num>>i & 1);
}
}
答案 1 :(得分:0)
试试这个,
#include <stdio.h>
int main()
{
int intNum = 13, intBin = 7;
unsigned i;
for (i = 1 << (intBin-1); i > 0; i = i / 2)
(intNum & i)? printf("1"): printf("0");
return 0;
}
答案 2 :(得分:0)
#include <stdio.h>
#include <limits.h>
#include <conio.h>
void printBin(int num, int bits){
unsigned n = (unsigned)num;
unsigned mask;
int bit_len = sizeof(n) * CHAR_BIT;
if(bits <= 0 || bits > bit_len)
return ;
for(mask = 0x1 << --bits; mask; mask >>= 1){
putchar(n & mask ? '1' : '0');
}
}
int main(void){
int intNum, intBits;
printf("\nEnter a integer number and number of bits :");
scanf("%d %d", &intNum, &intBits);
printf("\nInteger number in binary format :");
printBin(intNum, intBits);puts("");
getch();
return 0;
}