简体   繁体   中英

Arduino - How to convert uint16_t to Hex

I'm currently working on a sketch that will send data to 3 TLC5971 LED drivers. I need to accept a brightness level in the form uint16_t and then convert that value into two 8-bit hex numbers to pass to the LED drivers.

Example 65535 --> 0xFF and 0xFF

Is there any relatively easy way to do this? I've found several methods that return arrays of characters and whatnot but they don't seem to be easy to implement.

Does anyone have any experience doing anything similar?

Try this:

uint16_t value;
uint8_t msb = (value & 0xFF00U) >> 8U;
uint8_t lsb = (value & 0x00FFU);

Edit 1:
You could complicate matters and use a structure:

struct MSB_LSB
{
  unsigned int MSB : 8;
  unsigned int LSB : 8;
};
uint16_t value = 0x55aa;
uint8_t msb = ((MSB_LSB)(value)).MSB;
uint8_t lsb = ((MSB_LSB)(value)).LSB;

BTW, decimal, hexadecimal and octal are examples of representations . The representations are for humans to understand. The computer internally stores numbers in a representation convenient for the processor. So when you specify a decimal number, the compiler converts the decimal number into a value better suited for the processor. We humans, can represent the number in a representation that is easiest for us to understand.

uint16_t value = 0x1234;    // Use example with different high/low byte values
unsigned char high_byte = value >> 8;   // = 0x12
unsigned char low_byte = value & 0xFF;  // = 0x34

using a union:

typedef union
{
 unsigned short s;
 unsigned char b[2];
} short2bytes_t;

unsigned short value=65535;
unsigned char  MSB, LSB;

short2bytes_t s2b;
s2b.s = value;
MSB=s2b.b[1];
LSB=s2b.b[0];

printf("%d -> 0x%02X 0x%02X\n", value, MSB, LSB);

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