简体   繁体   English

在 C 中将 int 转换为 char

[英]Converting int to char in C

Right now I am trying to convert an int to a char in C programming.现在我正在尝试在 C 编程中将 int 转换为 char。 After doing research, I found that I should be able to do it like this:经过研究,我发现我应该可以这样做:

int value = 10;
char result = (char) value;

What I would like is for this to return 'A' (and for 0-9 to return '0'-'9') but this returns a new line character I think.我想要的是返回'A'(并且0-9返回'0'-'9'),但我认为这会返回一个换行符。 My whole function looks like this:我的整个功能如下所示:

char int2char (int radix, int value) {
  if (value < 0 || value >= radix) {
    return '?';
  }

  char result = (char) value;

  return result;
}

to convert int to char you do not have to do anything将 int 转换为 char 你不需要做任何事情

char x;
int y;


/* do something */

x = y;

only one int to char value as the printable (usually ASCII) digit like in your example:只有一个 int 到 char 值作为可打印(通常是 ASCII)数字,如您的示例中所示:

const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

int inttochar(int val, int base)
{
    return digits[val % base];
}

if you want to convert to the string (char *) then you need to use any of the stansdard functions like sprintf, itoa, ltoa, utoa, ultoa .... or write one yourself:如果要转换为字符串 (char *),则需要使用任何标准函数,如 sprintf、itoa、ltoa、utoa、ultoa .... 或自己编写一个:

char *reverse(char *str);
const char digits[] = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";

char *convert(int number, char *buff, int base)
{
    char *result = (buff == NULL || base > strlen(digits) || base < 2) ? NULL : buff;
    char sign = 0;


    if (number < 0)
    {
         sign = '-';

    }
    if (result != NULL)
    {
        do
        {
            *buff++ = digits[abs(number % (base ))];
            number /= base;
        } while (number);
        if(sign) *buff++ = sign;
        if (!*result) *buff++ = '0';
        *buff = 0;
        reverse(result);
    }
    return result;
}

A portable way of doing this would be to define a一种可移植的方法是定义一个

const char* foo = "0123456789ABC...";

where ... are the rest of the characters that you want to consider.其中...是您要考虑的其余字符。

Then and foo[value] will evaluate to a particular char .然后foo[value]将评估为特定的char For example foo[0] will be '0' , and foo[10] will be 'A' .例如foo[0]将是'0' ,而foo[10]将是'A'

If you assume a particular encoding (such as the common but by no means ubiquitous ASCII) then your code is not strictly portable.如果您假设特定编码(例如常见但绝不普遍存在的 ASCII),那么您的代码不是严格可移植的。

Characters use an encoding (typically ASCII) to map numbers to a particular character.字符使用编码(通常是 ASCII)将数字映射到特定字符。 The codes for the characters '0' to '9' are consecutive, so for values less than 10 you add the value to the character constant '0' .字符'0''9'的代码是连续的,因此对于小于 10 的值,您将该值添加到字符常量'0'中。 For values 10 or more, you add the value minus 10 to the character constant 'A' :对于 10 或更大的值,将值减 10 添加到字符常量'A'

char result;
if (value >= 10) {
    result = 'A' + value - 10;
} else {
    result = '0' + value;
}

Converting Int to Char将 Int 转换为 Char

I take it that OP wants more that just a 1 digit conversion as radix was supplied.我认为 OP 需要的不仅仅是 1 位转换,因为提供了radix


To convert an int into a string , (not just 1 char ) there is the sprintf(buf, "%d", value) approach.要将int转换为string (不仅仅是 1 char ),可以使用sprintf(buf, "%d", value)方法。

To do so to any radix, string management becomes an issue as well as dealing the corner case of INT_MIN要对任何基数执行此操作,字符串管理以及处理INT_MIN的极端情况都会成为问题


The following C99 solution returns a char* whose lifetime is valid to the end of the block.以下 C99 解决方案返回一个char* ,其生命周期有效到块的末尾。 It does so by providing a compound literal via the macro.它通过宏提供复合文字来实现。

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>

// Maximum buffer size needed
#define ITOA_BASE_N (sizeof(unsigned)*CHAR_BIT + 2)

char *itoa_base(char *s, int x, int base) {
  s += ITOA_BASE_N - 1;
  *s = '\0';
  if (base >= 2 && base <= 36) {
    int x0 = x;
    do {
      *(--s) = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"[abs(x % base)];
      x /= base;
    } while (x);
    if (x0 < 0) {
      *(--s) = '-';
    }
  }
  return s;
}

#define TO_BASE(x,b) itoa_base((char [ITOA_BASE_N]){0} , (x), (b))

Sample usage and tests样品使用和测试

void test(int x) {
  printf("base10:% 11d base2:%35s  base36:%7s ", x, TO_BASE(x, 2), TO_BASE(x, 36));
  printf("%ld\n", strtol(TO_BASE(x, 36), NULL, 36));
}

int main(void) {
  test(0);
  test(-1);
  test(42);
  test(INT_MAX);
  test(-INT_MAX);
  test(INT_MIN);
}

Output输出

base10:          0 base2:                                  0  base36:      0 0
base10:         -1 base2:                                 -1  base36:     -1 -1
base10:         42 base2:                             101010  base36:     16 42
base10: 2147483647 base2:    1111111111111111111111111111111  base36: ZIK0ZJ 2147483647
base10:-2147483647 base2:   -1111111111111111111111111111111  base36:-ZIK0ZJ -2147483647
base10:-2147483648 base2:  -10000000000000000000000000000000  base36:-ZIK0ZK -2147483648

Ref How to use compound literals to fprintf() multiple formatted numbers with arbitrary bases?参考如何使用复合文字来fprintf()具有任意基数的多个格式化数字?

Check out the ascii table查看ascii 表

The values stored in a char are interpreted as the characters corresponding to that table.存储在 char 中的值被解释为对应于该表的字符。 The value of 10 is a newline 10 的值是换行符

So characters in C are based on ASCII (or UTF-8 which is backwards-compatible with ascii codes).因此 C 中的字符基于ASCII (或向后兼容 ascii 代码的 UTF-8)。 This means that under the hood, "A" is actually the number "65" (except in binary rather than decimal).这意味着在引擎盖下,“A”实际上是数字“65”(二进制而不是十进制除外)。 All a "char" is in C is an integer with enough bytes to represent every ASCII character. C 中的所有“char”都是一个整数,它有足够的字节来表示每个 ASCII 字符。 If you want to convert an int to a char , you'll need to instruct the computer to interpret the bytes of an int as ASCII values - and it's been a while since I've done C, but I believe the compiler will complain since char holds fewer bytes than int .如果要将int转换为char ,则需要指示计算机将 int 的字节解释为 ASCII 值 - 自从我完成 C 以来已经有一段时间了,但我相信编译器会抱怨因为charint拥有更少的字节。 This means we need a function, as you've written.这意味着我们需要一个函数,正如你所写的。 Thus,因此,

if(value < 10) return '0'+value;
return 'A'+value-10;

will be what you want to return from your function.将是您想要从您的函数返回的内容。 Keep your bounds checks with "radix" as you've done, imho that is good practice in C.正如你所做的那样,用“基数”保持你的边界检查,恕我直言,这是 C 中的好习惯。

1. Converting int to char by type casting 1.通过类型转换将int转换为char

Source File charConvertByCasting.c源文件charConvertByCasting.c

#include <stdio.h>

int main(){
    int i = 66;              // ~~Type Casting Syntax~~
    printf("%c", (char) i); //  (type_name) expression
    return 0;
}

Executable charConvertByCasting.exe command line output:可执行charConvertByCasting.exe命令行输出:

C:\Users\boqsc\Desktop\tcc>tcc -run charconvert.c
B

Additional resources:其他资源:
https://www.tutorialspoint.com/cprogramming/c_type_casting.htm https://www.tutorialspoint.com/cprogramming/c_data_types.htm https://www.tutorialspoint.com/cprogramming/c_type_casting.htm https://www.tutorialspoint.com/cprogramming/c_data_types.htm

2. Convert int to char by assignment 2.通过赋值将int转换为char

Source File charConvertByAssignment.c源文件charConvertByAssignment.c

#include <stdio.h>

int main(){
    int i = 66;
    char c = i;
    printf("%c", c);
    return 0;
}

Executable charConvertByAssignment.exe command line output:可执行charConvertByAssignment.exe命令行输出:

C:\Users\boqsc\Desktop\tcc>tcc -run charconvert.c
B

You can do你可以做

char a;
a = '0' + 5;

You will get character representation of that number.您将获得该数字的字符表示。

Borrowing the idea from the existing answers, ie making use of array index.从现有答案中借用这个想法,即利用数组索引。 Here is a "just works" simple demo for "integer to char[]" conversion in base 10, without any of <stdio.h> 's printf family interfaces.这是一个“正常工作”的简单演示,用于以 10 为底的“整数到字符 []”转换,没有任何<stdio.h>printf系列接口。

Test:测试:

$ cc -o testint2str testint2str.c && ./testint2str
Result: 234789

Code:代码:

#include <stdio.h>
#include <string.h>

static char digits[] = "0123456789";

void int2str (char *buf, size_t sz, int num);


/*
  Test: 
        cc -o testint2str testint2str.c && ./testint2str
*/
int
main ()
{
  int num = 234789;
  char buf[1024] = { 0 };

  int2str (buf, sizeof buf, num);

  printf ("Result: %s\n", buf);


}

void
int2str (char *buf, size_t sz, int num)
{
  /*
     Convert integer type to char*, in base-10 form.
   */

  char *bufp = buf;
  int i = 0;

  // NOTE-1
  void __reverse (char *__buf, int __start, int __end)
  {
    char __bufclone[__end - __start];
    int i = 0;
    int __nchars = sizeof __bufclone;
    for (i = 0; i < __nchars; i++)
      {
    __bufclone[i] = __buf[__end - 1 - i];
      }
    memmove (__buf, __bufclone, __nchars);
  }

  while (num > 0)
    {
      bufp[i++] = digits[num % 10]; // NOTE-2
      num /= 10;
    }

  __reverse (buf, 0, i);

  // NOTE-3
  bufp[i] = '\0';
}

// NOTE-1:
//         "Nested function" is GNU's C Extension. Put it outside if not
//         compiled by GCC.
// NOTE-2:
//         10 can be replaced by any radix, like 16 for hexidecimal outputs.
//
// NOTE-3:
//         Make sure inserting trailing "null-terminator" after all things
//         done.

NOTE-1: "Nested function" is GNU's C Extension . NOTE-1: “嵌套函数”是 GNU 的C 扩展 Put it outside if not compiled by GCC.如果不是由 GCC 编译,则将其放在外面。

NOTE-2: 10 can be replaced by any radix, like 16 for hexidecimal outputs.注意2:10 可以用任何基数代替,例如 16 用于十六进制输出。

NOTE-3: Make sure inserting trailing "null-terminator" after all things done. NOTE-3:确保在所有事情完成后插入尾随“null-terminator”。

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

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