gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 15:14:03 29 4
gpt4 key购买 nike

我需要将 u16(unsigned int -2 byte) 值转换成字符串(不是 ascii)。如何将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

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

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

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

char *str = (char *) &my_uint16;

更新:为了完整起见,另一种表示 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];

关于c - 如何将 unsigned int(u16) 转换为字符串值(char *)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18073369/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com