0

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.

Skanda
  • 145
  • 4
  • 14
  • 1
    std::hex does not have any effect ? – Skanda Sep 09 '19 at 14:36
  • It is also easy to avoid "warning: use of old-style cast to ... } [-Wold-style-cast]"> (I'm sure we all turn on this warning!) I prefer a one line function (containing the cast) to convert, such as "uint scu(uint b) { return static_cast(b); }" The use of uint support auto-promotion ... so it only takes a few funcs. – 2785528 Sep 09 '19 at 15:00
  • @2785528 `uint scu(uint b) { return static_cast(b); }` is entirely useless. Just write static casts instead of hiding them behind some obscurely named (and possibly wrong) functions. – Max Langhof Sep 09 '19 at 15:07

2 Answers2

6

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
1

You are doing the conversion in a right way. The confusing output is the result of uint8_t being the same type as char on your platform. Try changing your code to

  std::cout << std::hex << (uint16_t)partA << std::endl; 
  std::cout << std::hex << (uint16_t)partB << std::endl;

And you will see

71
33
Dmitry Gordon
  • 2,229
  • 12
  • 20
  • This also can cause 2x: warning: use of old-style cast to ‘uint16_t’ {aka ‘short unsigned int’} [-Wold-style-cast] – 2785528 Sep 09 '19 at 14:55