[英]Printing ASCII Characters values in binary in C
我是C语言的新手,要完成分配,我必须打印最多5个ASCII字符的组合的8位二进制表示形式。 D3%= 01000100 00110011 00100101。
这是我的代码:
void ascii_to_binary(int * option_stats, char * ascii)
{
int i, j, num_value, count, binary[40], length, space=0; /* binary array length of 40 as */
length = strlen(ascii); /* 5*8 bit characters is 40 */
count = 8;
pos = 0
printf("Binary representation: ");
for (i = 0; i < length; i++)
{
num_value = ascii[i];
while(count > 0)
{
if((num_value%2) == 0)
{
binary[pos] = 0;
num_value = num_value/2;
count--;
pos++;
}
else
{
binary[pos] = 1;
num_value = num_value/2;
count--;
pos++;
}
}
count = 8; /*resets loop counter*/
}
for(j = pos-1; j >= 0; j--)
{
printf("%d", binary[j]);
space++;
if(space == 8)
{
printf(" "); /*white space between bytes*/
}
}
read_rest_of_line(); /*used as part of the larger program as a whole,
please ignore*/
}
我输入的ASCII字符是通过单独的函数传递的,代码如下:
void run_ascii_binary(void)
{
char input[MAX_STRING_INPUT + EXTRA_SPACES], ascii;
int option_stats;
printf("ASCII to Binary Generator\n");
printf("-------------------------\n");
printf("Enter a String (1-5 characters): ");
if (fgets(input, MAX_STRING_INPUT+EXTRA_SPACES, stdin) != NULL)
{
sscanf(input, "%s", &ascii);
}
ascii_to_binary(&option_stats, &ascii);
}
我的问题是要打印实际的二进制文件。
我得到的输出是:00100101 11001100 01000100,其中第一个字节和第三个字节的顺序错误。 使它以正确顺序打印的任何提示都很棒!
谢谢!
ascii
需要足够大以容纳5个char
和一个\\0
。
char ascii[5+1];
...
sscanf(input, "%5s", &ascii);
初始化option_stats
int option_stats = 0;
取消注释length = strlen(ascii);
。 上一行的未终止注释正在将其注释掉。
@LtWorf是正确的,OP应该精确地循环8次。
// while(num_value > 0) {
int bit;
int counti = count; /// see below
for (i=8; i-- > 0; ) {
此外,这些位是从最低有效位到最高位被累加的,但是您想要最大到最低地显示它们。 因此,以相反的顺序将它们累积在您的字符串中。
// In two places
// binary[count] = ...
binary[counti] = ...
还有其他清理代码的方法,但这是5个主要问题。
while(num_value > 0)
这是错误的,字符也可以是负数。 您最好只迭代8次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.