简体   繁体   English

如何将unsigned int(u16)转换为字符串值(char *)?

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

I need to convert u16(unsigned int -2 byte) value into string (not ascii). 我需要将u16(无符号int -2字节)值转换为字符串(不是ascii)。 How to convert unsigned int(u16) into string value(char *)? 如何将unsigned int(u16)转换为字符串值(char *)?

/* 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_t is as a series of four hexadecimal digits, requiring 4 chars. 更新:为了完整性,另一种呈现uint16_t是一系列四个十六进制数字,需要4个字符。 Skipping the WE_REALLY_WANT_A_POINTER ordeal, here's the code: 跳过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];

A uint16_t value only requires two unsigned char objects to describe it. uint16_t值只需要两个unsigned char对象来描述它。 Whether the higher byte comes first or last depends on the endianness of your platform: 高字节是先到还是最后取决于平台的字节顺序

// 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

你可以使用sprintf

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

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字符串,所以不要做任何危险的事情。

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

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