Losing Leading bits Splitting up Long var into bytes

Hey guys n gals,

I’ve come across a problem that is rather annoying and I can’t seem to figure out a solution to it. Here is the scenario.

I am reading in a 24 bit number and trying to store its 3 byte components into an array. The problem I have run into occurs during bit shifting. Whenever a byte starts with a ‘0’, its gets dropped and messes up the entire value.

Here is my code:

  for (n = 0; n < 3; n++) 
  {
    //SEND ADC VOLTAGE VALUE TO PC FOR PROCESSING
    outgoingByte[n] = getByte(adcvalue,n);
    mySerial.print(outgoingByte[n], HEX);
  }

byte getByte(unsigned long int x, int n)
{
    return (x >> ((2-n) << 3)) & 0xFF; //MSB first
}

If I enter say:

unsigned long int adcvalue = 0x290B0B;

The output is:

29BB

which makes sense, but how do I keep the leading zero when trying to extract bytes from a value?

If I enter say:

unsigned long int adcvalue = 0x29B0B0;

Then the output is perfect.

Any help would be appreciated.
Best
Rob

Hmmmm

unsigned long int x

Oh yea it should be

unsigned long int adcvalue = 0x00290B0B

32 bits. But that doesn't help with the problem..

OHHHH, I think I might be onto something. I'll try shifting to the LSB side

32 bits. But that doesn't help with the problem..

OHHHH, I think I might be onto something. I'll try shifting to the LSB side

The problem is not with the values that you are getting. It's with how you are printing them. 00, 29, 0B, 0B will print as 29BB if you don't do anything to print them differently.

TechnicRC: which makes sense, but how do I keep the leading zero when trying to extract bytes from a value?

When you go to print it, check if the value is less than 0x10. If so, print the leading 0.

You guys are awesome, got it!

Here is the working code:

  for (n = 0; n < 3; n++) 
  {
    //SEND ADC VOLTAGE VALUE TO PC FOR PROCESSING
    outgoingByte[n] = getByte(adcvalue,n);
    //print leading zero if values is less than 10
    if(outgoingByte[n] < 16)
    {
      mySerial.print(0,HEX);
      Serial.print(0,HEX);
    }
    mySerial.print(outgoingByte[n],HEX);
    Serial.print(outgoingByte[n],HEX);
  }
      mySerial.print(0,HEX);
      Serial.print(0,HEX);

Is printing 0 in HEX any different from printing it base 2 or 10 or 3.14159?

if(outgoingByte[n] < 16)

You’re printing in HEX, so wouldn’t it make more sense to check it again the HEX value?