简体   繁体   English

将整数添加为char以在C中创建字符串

[英]Adding integers as char to create a string in C

I wanted to ask if there is a way to add integers as char values and create a string. 我想问是否有一种方法可以将整数添加为char值并创建一个字符串。 I have written some code but only last digit is detected 我已经写了一些代码,但是只检测到最后一位数字

void binary(int decimal) {
  int modulus;
  char bin[9];
  while (decimal != 0) {
    modulus = decimal % 2;
    sprintf(bin, "%d", modulus);
    if (modulus == 1) {
      decimal--;
    }
    decimal = decimal / 2;
  }
  puts(bin);
}

If the decimal is 10 then the holds only 1 instead 0101 . 如果十进制为10则仅保留1而不是0101 How can I fix it? 我该如何解决? I am using Turbo C++ 3.0. 我正在使用Turbo C ++ 3.0。

of course, you're printing on the same bin location, not moving your "cursor". 当然,您要在相同的bin位置上打印,而不要移动“光标”。

Declare a pointer on the string and increment it after each sprintf , should work, since sprintf issues only 1 digit + null-termination char. 在字符串上声明一个指针,并在每个sprintf之后将其递增,因为sprintf仅发出1位数字+空终止char。

char bin[9];
char *ptr = bin;
  while (decimal != 0) {
    modulus = decimal % 2;
    sprintf(ptr, "%d", modulus);
    ptr++;

that generates the string, but reversed (because lower bits are processed first). 生成字符串,但是反转(因为低位首先被处理)。 Just print it reversed or reverse it afterwards. 只需将其打印反转或之后反转即可。

 int l = strlen(bin);
 for (i=0;i<l;i++)
 {
     putc(bin[l-i-1]);
 }
 putc("\n");

Here is a function that prints a decimal as binary: 这是一个将小数打印为二进制的函数:

void print_binary(int num)
{
    int pos = (sizeof(int) * 8) - 1;
    printf("%10d: ", num);

    for (int i = 0; i < (int)(sizeof(int) * 8); i++) {
        char c = num & (1 << pos) ? '1' : '0';
        putchar(c);
        if (!((i + 1) % 8))
            putchar(' ');
        pos--;
    }
    putchar('\n');
}

output: 输出:

        42: 00000000 00000000 00000000 00101010

This is exactly your function with slight modifications and comments. 只需稍加修改和注释,这就是您的功能。

The binary string is still reversed though. 二进制字符串仍然是相反的。

void binary(int decimal) {
  int modulus;
  char bin[9];
  char temp[2];   // temporary string for sprintf

  bin[0] = 0;     // initially binary string set to "" (empty string)

  while (decimal != 0) {
    modulus = decimal % 2;

    sprintf(temp, "%d", modulus);  // print '1' or '0' to temporary string
    strcat(bin, temp);             // concatenate temporary string to bin

    if (modulus == 1) {
      decimal--;
    }
    decimal = decimal / 2;
  }
  puts(bin);
}

There are more efficient ways to achieve this, especially makeing use of the left shift operator ( << ), that way you can construct the binary string directly without needing to reverse it at the end. 有更有效的方法来实现此目的,尤其是利用左移位运算符( << ),这样您就可以直接构造二进制字符串,而无需在最后将其反向。

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

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