#include<stdio.h>
int main()
{
long int decimalNumber,remainder,quotient;
int binaryNumber[100],i=1,j;
printf("Enter any decimal number: ");
scanf("%ld",&decimalNumber);
quotient = decimalNumber;
while(quotient!=0)
{
binaryNumber[i++]= quotient % 2;
quotient = quotient / 2;
}
printf("Equivalent binary value of decimal number %d: ",decimalNumber);
for(j = i -1 ;j> 0;j--)
printf("%d",binaryNumber[j]);
return 0;
}
我想以8位二进制形式输出,但结果如下所示,C中是否有任何运算符可以将7位数据转换为其等效的8位数据?谢谢
样本输出:
输入任何十进制数: 50 十进制数的等效二进制值50: 110010
需要输出的是00110010
,这是8位,如何在MSB位置附加一个零?
发布于 2015-04-19 10:43:06
一种非常方便的方式,它有一个函数,以字符串的形式返回二进制表示。这允许在普通的printf
格式字符串中使用二进制表示形式,而不是在当前游标位置吐出比特。要指定确切的数字数,必须将二进制字符串填充到所需的位置数(例如8、16、32.)。下面使用一个static
变量来允许缓冲区的返回,但是通过动态分配缓冲区的空间可以很容易地实现相同的变量。不需要预处理器检查,因为您可以简单地将缓冲区的长度硬连接到64 + 1
,但是为了完整起见,包含了x86/x86_64
的检查,并相应地设置了BITS_PER_LONG
。
#include <stdio.h>
#if defined(__LP64__) || defined(_LP64)
# define BUILD_64 1
#endif
#ifdef BUILD_64
# define BITS_PER_LONG 64
#else
# define BITS_PER_LONG 32
#endif
char *binstr (unsigned long n, size_t sz);
int main (void) {
printf ("\n 50 (decimal) : %s (binary)\n\n", binstr (50, 8));
return 0;
}
/* returns pointer to binary representation of 'n' zero padded to 'sz'. */
char *binstr (unsigned long n, size_t sz)
{
static char s[BITS_PER_LONG + 1] = {0};
char *p = s + BITS_PER_LONG;
register size_t i;
if (!n) {
*s = '0';
return s;
}
for (i = 0; i < sz; i++)
*(--p) = (n>>i & 1) ? '1' : '0';
return p;
}
输出
$ ./bin/bincnv
50 (decimal) : 00110010 (binary)
注意:由于静态缓冲区,您不能在同一个printf
语句中重复调用。如果动态分配,则可以在同一个printf
语句中任意多次调用该函数。
另外,请注意,如果您不关心将二进制返回到任何特定长度,而只希望二进制表示以最重要的位开始,则可以使用以下更简单的版本:
/* simple return of binary string */
char *binstr (unsigned long n)
{
static char s[BITS_PER_LONG + 1] = {0};
char *p = s + BITS_PER_LONG;
if (!n) {
*s = '0';
return s;
}
while (n) {
*(--p) = (n & 1) ? '1' : '0';
n >>= 1;
}
return p;
}
发布于 2015-04-19 10:10:34
修改代码如下所示:
quotient = quotient / 2;
}
/* ---- Add the following code ---- */
{
int group_size = 8; /* Or CHAR_BIT */
int padding = group_size - ((i-1) % group_size); /* i was inited with 1 */
if(padding != group_size) {
/* Add padding */
while(padding-- != 0) binaryNumber[i++] = 0;
}
}
/* ------- Modification ends -------- */
printf("Equivalent binary value of decimal number %d: ",decimalNumber);
此代码计算打印该数字所需的填充位数,并将填充位填充为0。
现场演示
如果您想要7位答案,请将group_size
更改为7。
https://stackoverflow.com/questions/29728344
复制相似问题