简体   繁体   中英

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

I need to convert u16(unsigned int -2 byte) value into string (not ascii). How to convert unsigned int(u16) into string value(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. Skipping the WE_REALLY_WANT_A_POINTER ordeal, here's the code:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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