怎么编写一个简单的输出二进制的程序
1个回答
展开全部
Here is a quick hack to demonstrate techniques to do what you want.
#include <stdio.h> // printf
#include <string.h> // strcat
#include <stdlib.h> // strtol
const char *byte_to_binary
(
int x
)
{
static char b[9] = {0};
int z;
for (z = 256; z > 0; z >>= 1)
{
strcat(b, ((x & z) == z) ? "1" : "0");
}
return b;
}
int main(void)
{
{
// binary string to int
char *tmp;
char *b = "0101";
printf("%d\n", strtol(b, &tmp, 2));
}
{
// byte to binary string
printf("%s\n", byte_to_binary(5));
}
return 0;
}
#include <stdio.h> // printf
#include <string.h> // strcat
#include <stdlib.h> // strtol
const char *byte_to_binary
(
int x
)
{
static char b[9] = {0};
int z;
for (z = 256; z > 0; z >>= 1)
{
strcat(b, ((x & z) == z) ? "1" : "0");
}
return b;
}
int main(void)
{
{
// binary string to int
char *tmp;
char *b = "0101";
printf("%d\n", strtol(b, &tmp, 2));
}
{
// byte to binary string
printf("%s\n", byte_to_binary(5));
}
return 0;
}
参考资料: http://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询