C语言 如何将无符号整数(u16)转换为字符串值(char *)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18073369/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 07:04:04  来源:igfitidea点击:

How to convert unsigned int(u16) into string value(char *)?

c

提问by Sujatha

I need to convert u16(unsigned int -2 byte) value into string (not ascii). How to convert unsigned int(u16) into string value(char *)?

我需要将 u16(unsigned int -2 byte) 值转换为字符串(不是 ascii)。如何将无符号整数(u16)转换为字符串值(char *)?

回答by Nerius

/* The max value of a uint16_t is 65k, which is 5 chars */
#ifdef  WE_REALLY_WANT_A_POINTER
char *buf = malloc (6);
#else
char buf[6];
#endif

sprintf (buf, "%u", my_uint16);

#ifdef WE_REALLY_WANT_A_POINTER
free (buf);
#endif

Update: If we do not want to convert the number to text, but to an actual string (for reasons that elude my perception of common sense), it can be done simply by:

更新:如果我们不想将数字转换为文本,而是转换为实际的字符串(出于我对常识的看法),可以简单地通过以下方式完成:

char *str = (char *) (intptr_t) my_uint16;

Or, if you are after a string that is at the same address:

或者,如果您要查找位于同一地址的字符串:

char *str = (char *) &my_uint16;

Update: For completeness, another way of presenting an uint16_tis as a series of four hexadecimal digits, requiring 4 chars. Skipping the WE_REALLY_WANT_A_POINTERordeal, here's the code:

更新:为了完整起见,另一种表示 an 的方式uint16_t是一系列四个十六进制数字,需要 4 个字符。跳过WE_REALLY_WANT_A_POINTER考验,这是代码:

const char hex[] = "0123456789abcdef";
char buf[4];
buf[0] = hex[my_uint16 & f];
buf[1] = hex[(my_uint16 >> 4) & f];
buf[2] = hex[(my_uint16 >> 8) & f];
buf[3] = hex[my_uint16 >> 12];

回答by dreamlax

A uint16_tvalue only requires two unsigned charobjects to describe it. Whether the higher byte comes first or last depends on the endiannessof your platform:

一个uint16_t值只需要两个unsigned char对象来描述它。高字节是第一个还是最后一个取决于您平台的字节序

// if your platform is big-endian
uint16_t value = 0x0A0B;
unsigned char buf[2];

buf[0] = (value >> 8); // 0x0A comes first
buf[1] = value;


// if your platform is little-endian
uint16_t value = 0x0A0B;
unsigned char buf[2];

buf[0] = value;
buf[1] = (value >> 8); // 0x0A comes last

回答by One Man Crew

You can use sprintf:

您可以使用sprintf

sprintf(str, "%u", a); //a is your number ,str will contain your number as string

回答by Henrik

It's not entirely clear what you want to do, but it sounds to me that what you want is a simple cast.

不完全清楚你想做什么,但在我看来你想要的是一个简单的演员。

uint16_t val = 0xABCD;
char* string = (char*) &val;

Beware that the string in general is not a 0-byte terminated C-string, so don't do anything dangerous with it.

请注意,字符串通常不是以 0 字节结尾的 C 字符串,所以不要对它做任何危险的事情。