Search code examples
c++bit-shiftmasking

How to change uint16_t to two uint8_t?


How to convert one uint16_t to two parts?

uint16_t value = 0x7133;
uint8_t partA = (uint8_t)((value & 0xFF00) >> 8);
uint8_t partB = (uint8_t)(value & 0x00FF);
std::cout << std::hex << partA << std::endl; 
std::cout << std::hex << partB << std::endl;

For the above code I get partA as q and partB as 3 instead of 0x71 and 0x33.


Solution

  • Putting a uint8_t into cout gets the operator<<(const char&) picked which prints letters and 71 and 33 happen to be the ascii codes of q and 3. If you want to see the number, you have to make it pick a different overload:

    uint16_t value = 0x7133;
    uint8_t partA = static_cast<uint8_t>((value & 0xFF00) >> 8);
    uint8_t partB = static_cast<uint8_t>(value & 0x00FF);
    std::cout << std::hex << static_cast<int>(partA) << std::endl; 
    std::cout << std::hex << static_cast<int>(partB) << std::endl;
    

    std::hex does not have any effect

    It does have an effect, but not on letters. There is no hex formatting applied for eg q. Once you pick an overload that prints numbers the numbers will be printed as hex.

    PS: I changed your c-style casts to static_casts. C-style casts are a red flag, and they should make you panic, because most often they are just hiding a bug.