简体   繁体   English

在 C 中打印一个 Char 整数数组

[英]Print a Char Array of Integers in C

For class, I am required to create a function that converts an Integer into it's corresponding Binary number.对于类,我需要创建一个将整数转换为其相应二进制数的函数。 However, I am forced to use the given main and parameters for the to_binary function.但是,我不得不为 to_binary 函数使用给定的 main 和参数。 The whole problem requires me to print out the 32 bit binary number, but to break it up, I am just trying to print out the Char Array, that I thought I filled with Integers (perhaps the issue).整个问题需要我打印出 32 位二进制数,但要分解它,我只是想打印出 Char 数组,我以为我用整数填充了它(也许是问题)。 When I do compile, I receive just a blank line (from the \\n) and I am wondering how I can fix this.当我编译时,我只收到一个空行(来自 \\n),我想知道如何解决这个问题。 All I want to do is to be able to print the binary number for 5 ("101") yet I can't seem to do it with my professor's restrictions.我想要做的就是能够打印 5(“101”)的二进制数,但我似乎无法在教授的限制下做到这一点。 Remember: I cannot change the arguments in to_binary or the main, only the body of to_binary.请记住:我不能更改 to_binary 或 main 中的参数,只能更改 to_binary 的主体。 Any help would be greatly appreciated.任何帮助将不胜感激。

#include<stdio.h>

void to_binary(int x, char c[]) {

    int j = 0;

    while (x != 0) {
        c[j] x = x % 2;
        j++;
    }
    c[33] = '\0';
}

int main() {
    int i = 5;
    char b[33];
    to_binary(i,b);
    printf("%s\n", b);
}

the problem is in the code below:问题出在下面的代码中:

while (x != 0) {
  c[j] = x % 2;  // origin: c[j] x = x % 2; a typo?
  j++;
}

the result of x % 2 is a integer, but you assigned it to a character c[j] —— integer 1 is not equal to character '1' . x % 2的结果是一个整数,但是你把它赋给了一个字符c[j] —— 整数1不等于字符'1'

If you want to convert a integer(0-9) to a character form, for example: integer 7 to character '7' , you can do this:如果要将 integer(0-9) 转换为字符形式,例如: integer 7 to character '7' ,可以执行以下操作:

int integer = 7;
char ch = '0' + integer;

One of the previous answers has already discussed the issue with c[j] x = x % 2;先前的答案之一已经讨论了c[j] x = x % 2; and the lack of proper character conversion.以及缺乏适当的字符转换。 That being said, I'll instead be pointing out a different issue.话虽如此,我将指出一个不同的问题。 Note that this isn't a specific solution to your problem, rather, consider it to be a recommendation.请注意,这不是针对您的问题的特定解决方案,而是将其视为建议。

Hard-coding the placement of the null-terminator is not a good idea.硬编码空终止符的位置不是一个好主意。 In fact, it can result in some undesired behavior.事实上,它可能会导致一些不受欢迎的行为。 Imagine I create an automatic char array of length 5. In memory, it might look something like this:想象一下,我创建了一个长度为 5 的自动字符数组。在内存中,它可能看起来像这样:

Values = _ _ _ _ _
Index  = 0 1 2 3 4

If I were to populate the first three indexes with '1', '0', and '1', the array might look like so:如果我用“1”、“0”和“1”填充前三个索引,数组可能如下所示:

Values = 1 0 1 _ _
Index  = 0 1 2 3 4

Let's say I set index 4 to contain the null-terminator.假设我将索引 4 设置为包含空终止符。 The array now looks like so:数组现在看起来像这样:

Values = 1 0 1 _ \0
Index  = 0 1 2 3 4

Notice how index three is an open slot?注意索引 3 是一个空槽吗? This is bad.这不好。 In C/C++ automatic arrays contain garbage values by default.在 C/C++ 中,默认情况下自动数组包含垃圾值。 Furthermore, strings are usually printed by iterating from character to character until a null-terminator is encountered.此外,字符串通常是通过从一个字符到另一个字符的迭代来打印的,直到遇到一个空终止符。

If the array were to look like it does in the previous example, printing it would yield a weird result.如果数组看起来像在前面的例子中那样,打印它会产生一个奇怪的结果。 It would print 1, 0, 1, followed by an odd garbage value.它将打印 1, 0, 1,后跟一个奇数垃圾值。

The solution is to set the null-terminator directly after the string ends.解决方法是在字符串结束后直接设置空终止符。 In this case, you want your array to look like this:在这种情况下,您希望数组如下所示:

Values = 1 0 1 \0 _
Index  = 0 1 2 3  4

The value of index 4 is irrelevant, as the print function will terminate upon reading index 3.索引 4 的值无关紧要,因为打印函数将在读取索引 3 时终止。

Here's a code example for reference:下面是一个代码示例供参考:

#include <stdio.h>

int main() {

    const size_t length = 4;
    char binary[length];
    size_t i = 0;

    while (i < length - 1) {
        char c = getchar();
        if (c == '0' || c == '1')
            binary[i++] = c;
    }
    binary[i] = '\0';

    puts(binary);

    return 0;
}

This is the answer to your question.这是你的问题的答案。

void to_binary(int x, char c[]) {
    int i =0;
    int j;
    while(x) {
        /* The operation results binary in reverse order. 
         * so right-shift the entire array and add new value in left side*/
        for(j = i; j > 0; j--) {    
            c[j] = c[j-1];
        }
        c[0] = (x%2) + '0';
        x = x/2;
        i++;
    }
    c[i]=0; 
}
#include<stdio.h>
int binary(int x)
{
    int y,i,b,a[100];
    if(x<16)
    {
            if(x%2==1)
                    a[3]=1;
            if(x/2==1||x/2==3 || x/2==5 || x/2==7)
                    a[2]=1;
            if(x>4 && x<8)
                    a[1]=1;
            else if(x>12 && x<16)
                    a[1]=1;
            if(x>=8)
                    a[0]=1;
    }
    for(i=0;i<4;i++)
            printf("\t%d",a[i]);
    printf("\n");
}

int main()
{
    int c;
    printf("Enter the decimal number (less than 16 ):\n");
    scanf("%d",&c);
    binary(c);
}

this code might help it will simply convert the decimal number less than 16 into the 4 digit binary number.if it contains any error than let me know此代码可能会有所帮助,它将小于 16 的十进制数简单地转换为 4 位二进制数。如果它包含任何错误,请告诉我

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM