problem with right shifting bits???

I have a 16 bit variable and I want to read the high byte as an 8-bit value. I tried right shifting by 8 bits and casting the value as a uint8_t type. But I do not get the correct value, at least I don’t get what I was expecting.

Here is some code:

  uint16_t dataLength, dataLength2;
  
  Serial.begin(9600);
  
  dataLength = 0x017F;
  Serial.println(dataLength, HEX);
  dataLength2 = dataLength >> 8;
  Serial.println  (((dataLength2),HEX));
  Serial.println((uint8_t) dataLength, HEX);

I expected to get 0x01 as the high byte value, but I am getting 0x16!!! What am I doing wrong with this seemingly simple operation?!?

-Tony

You have bad brackets in

  Serial.println  (((dataLength2),HEX));

which leads to a warning

Somewhere\AppData\Local\Arduino15\packages\arduino\hardware\avr\1.6.21\cores\arduino/Print.h:30:13: warning: left operand of comma operator has no effect [-Wunused-value]

If you drop them, everything works as expected.

uint16_t dataLength, dataLength2;

void setup() {
  Serial.begin(250000);

  dataLength = 0x017F;
  Serial.println(dataLength, HEX);
  dataLength2 = dataLength >> 8;
  Serial.println((dataLength2), HEX);
  Serial.println((uint8_t) dataLength, HEX);
}
void loop() {}
17F
1
7F

You have bad brackets

Thanks! That was weird. I got no warnings from the compiler. That fixed it!!

By default, the compiler warnings are turned off - I suspect the reason is to keep hoards of people from seeing a warning that isn't a problem (since we're all copy-pasting half-assed code all over, which is often full of stuff that gets warnings) and screaming on forums about the warnings, not knowing the difference between a warning and an error.

Anyone whose sketch is not doing what they expect should turn up their warning level to ALL. Often that will put out a warning that indicates a common coding mistake that isn't technically an error.

How about:

 void setup()
{
  Serial.begin(9600);
  uint16_t dataLength;

  dataLength = 0x017F;
  Serial.println(dataLength, HEX);
  Serial.println(highByte(dataLength),HEX);
  Serial.println(lowByte(dataLength),HEX);
}
void loop(){}

Arhodes01075: I expected to get 0x01 as the high byte value, but I am getting 0x16!!!

No, you are getting 16 ;)

Serial.print() don’t print leading zeros, 0x01 prints 1. Try:

void setup()
{
  Serial.begin(9600);
  uint16_t dataLength;
 
  dataLength = 0x017F;
  Serial.println(dataLength, HEX);
  if(highByte(dataLength) < 0x10)
    Serial.print('0');
  Serial.println(highByte(dataLength),HEX);
  if(lowByte(dataLength) < 0x10)
    Serial.print('0');
  Serial.println(lowByte(dataLength),HEX);
}
void loop(){}

https://www.arduino.cc/reference/en/language/functions/bits-and-bytes/highbyte/