Why wont this code work?

I want to separate a hexadecimal value into 3 bytes but the code is outputting
Original Hex Value: 0x5EEF
Decimal Values: {0, 94, 239}
The byte I'm using to test is 0xbb5eef

I don't see a flaw in the code and I am wondering why only the first byte is incorrect.

void setup() {
  // Original hexadecimal value
  unsigned int hexValue = 0xbb5eef;

  // Extract individual bytes
  byte byte1 = (hexValue >> 16) & 0xFF;
  //187
  byte byte2 = (hexValue >> 8) & 0xFF;
  //94
  byte byte3 = hexValue & 0xFF;
  //239


  int decimalValues[] = {byte1, byte2, byte3};

  // Print the original value and the array of decimal values
  Serial.begin(9600);
  Serial.print("Original Hex Value: 0x");
  Serial.println(hexValue, HEX);
  Serial.print("Decimal Values: {");
  for (int i = 0; i < 3; ++i) {
    Serial.print(decimalValues[i]);
    if (i < 2) {
      Serial.print(", ");
    }
  }
  Serial.println("}");
}

void loop() {
  // pass
}

Actually most people would see that as being THREE bytes!
An unsigned int is TWO bytes long!
Work on those problems and see if you can get it to work.

I would imagine that the size of an unsigned int is only 16 bits on whatever board you're trying this with. Crank up your warning level and you'll get a 'large integer implicitly truncated to unsigned type' warning.

RGB888 to RGB565

  • mask 5 MSB of 8 bit RED: 0xff & b1111 1000
  • shift left 8 to make room for 6 GRN and 5 BLU
  • mask 6 MSB of 8 bit GRN: 0xff & b1111 1100
  • shit left 3 (to leave room for 5 BLU)
  • mask 5 MSB of 8 bit BLU: 0xff & b1111 1000
  • shift RIGHT 3 (because 11 bits to the left are R and G)
  • fin

RGB888 0xaabbcc (b 1010 1010 1011 1011 1100 1100)
to
RGB565 0xadd9 (b1010 1101 1101 1001)

  10101010 red 0xAA
& 11111000 mask 5
  ---------
  10101xxx 5red
  10101xxx00000000 5red << 8

  10111011 grn 0xBB
& 11111100 mask 6
  --------
  101110xx 6grn
  xxxxx101110xxzzz 6grn << 3

  11001100 blu 0xCC
& 11111000 mask 5
  --------
  11001xxx 5blu >> 3
  xxxxxyyyyyy11001

  1010 1101 1101 1001 result 0xadd9

Backwards (RGB565 to RGB888) will lose LSBs due to shifting (and padding with zeroes)

0x5EEF

RGB565 0x5EEF to RGB888 0xRRGGBB

b 0101 1110 1110 1111 (0x5EEF)
mask red 5: 01011
shift left 3 0101 1xxx (0x58) = 88 dec
mask grn 6 110111
shift left 2 1101 11xx (0xdc) = 220 dec
mask blu 5: 01111
shift left 3 0111 1xxx (0xf8) = 248 dec

0x58 DC F8

should be

  unsigned long hexValue = 0xbb5eef;

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.