Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c

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

like image 580
Sujatha Avatar asked Dec 12 '22 12:12

Sujatha


2 Answers

/* 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];
like image 141
Nerius Avatar answered Dec 14 '22 00:12

Nerius


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
like image 20
dreamlax Avatar answered Dec 14 '22 02:12

dreamlax