我有一个无符号的int值

u_int_variable = 43981; // This is equal to ABCD in HEX

我可以使用ABCD以十六进制格式将其打印到控制台
printf("Value in Hex is %X", u_int_variable);

// Output : Value in Hex is ABCD

我该如何转换和分离这样
unsigned char uhex, lhex;

uhex = 0xAB; and lhex = 0xCD;

最佳答案

uhex = static_cast<unsigned char>(u_int_variable >> 8);
lhex = static_cast<unsigned char>(u_int_variable & 0xFF);

或者,对于> 32位无符号整数绝对安全:
uhex = static_cast<unsigned char>((u_int_variable >> 8) & 0xFF);

07-26 03:07