# Binary code to decimal number

Hi I am absolutely new to this. So please forgive me if my question seems kinda stupid. I have a can shield that is supposed to send a signal. The signal the shield receives is Binary code and the signal I want to transmit is supposed to be a decimal number. The number is in the received signal. It is 8 bit long and starts at bit 16. The factor is 0.01 and the Offset -1.27 and the sign is on bit 14

Can you provide a picture because that is worth a thousand words…

if the sign bit is at 14 and the number is 8 long and starts at 16 the sign will be overwritten???

``````int val = 0;
int sign = 1;

for (int i=0; i<16; i++)
{
if (i == 14)
{
if (getBit() == 1) sign = -1;
}
val = val * 2;
val = val + getBit();
}

val = val * sign;

float value = val * 0.01;
``````

Thank you for your quick Reply. Sorry I cant provide a Picture. But I think I can specify my Problem a bit better now. I have a uint64_t. All Data I Need are on bit 14(the sign) and bit 16 to 24 everything else is data about stuff I don't care about. I want to Serial.printIn the number in those bits. Offset is still -1.27 and the factor is 0.01.

Nikosc:
I have a uint64_t. All Data I Need are on bit 14(the sign)

You can extract the 15-bit signed integer like:

``````uint64_t theCode = wherever_it_comes_from;

int16_t theNumber= (int16_t)(theCode << 1);  // shift up, so bit14->bit15 == sign bit, cast to signed int

theNumber= theNumber >> 1;  // shift number back down. This is now a signed number -16384 .. 16383

// not sure what you mean by "Offset is still -1.27 and the factor is 0.01"
// - so this is a guess:

float value= ((float)theNumber * 0.01) - 1.27;
Serial.println( value );        // print value as floating point
Serial.println( (int)value ); // print value as an integer
``````

Yours,
TonyWilk

You want to use Serial.print to send data over the CAN bus? Or to print e.g. to the serial monitor?

Regardless from the answer to the above, maybe this snippet helps to understand how to extract the individual bytes from your 64 bit number.

``````void setup()
{
Serial.begin(57600);

uint64_t x = 0x0123456789ABCDEF;

// pointer to the indivual bytes of the uint64_t
byte *ptr;
ptr = (byte*)&x;

// loop through the bytes
for (byte cnt = 0; cnt < sizeof(x); cnt++)
{
Serial.println(ptr[cnt], HEX);

}
}
``````

Note that the numbers are printed in the reversed sequence due to the way they are stored in memory.