Problem casting data

Edit I figured out my problem, see my post below

I am having a very odd problem indeed! I can’t seem to cast data correctly. Here is my code

// Converts a 12 bit value (i.e. one taken from I2c) to a signed value

#define SIGN_12(value)  (((value) bitand 0x7FF) + (((value) bitand 0x800) << 4)) 

void setup(){
    Serial.begin(115200);
}

void loop(){
    uint16_t ui12 = 0xFFF;
    int16_t out;
    delay(1000);

    Serial.print(ui12); Serial.write('\t'); Serial.print(ui12, BIN);
    ui12 = SIGN_12(ui12);
    Serial.write('\t'); Serial.print(ui12, BIN);
    out = (int16_t) ui12;
    Serial.write('\t'); Serial.print(out, BIN);
    Serial.write('\t'); Serial.print(out);

    Serial.println();
}

I’m getting this as the output

4095 111111111111 1000011111111111 11111111111111111000011111111111 -30721

Process:

  • it starts as 4095
  • You can see the binary looks correct
  • the MSB is then moved to the left by 4 places, so that it is now at the MSB for an integer. (should be negative 2044 or something)
  • when it is cast as an int16_t, everything goes haywire.

From everything I know about casting, this is completely wrong! Any thoughts would be helpful

Edit
I just realized, it is treating it like it’s a 32 bit integer! This is a pretty serious bug, correct?

Edit2
It seems I have to go back to school and don’t know how to convert data to a signed integer… stay tuned…

whats the bitand? should that be & as per this?? http://docs.spark.io/firmware/#bitwise-operators-bitwise-and

Another thing… I did spend days debugging once because i didn’t realize that when you do

uint8_t number = 0b00110011
serial.print(number, BIN);

it output 110011, so when you combine lots one after the other you loose lots of 0’s same for hex too

Ok, I got the correct code

#define SIGN_12(x)  ((x >> 11) == 0 ? x : -1 ^ 0xFFF | x)    

With this I just use SIGN_12(value) to do a sign on any length.

1 Like