# Help isolating individual bytes from a double or float variable

Hi all

I'm struggling to get a section of code working on my Arduino Uno.

I have a double variable (eg. var = 3.14) and would like to isolate the individual bytes.

I'm aware the Arduino uses 4 bytes to store this value and I would like to take the individual hex data and store in 4 separate variables as described below.

Example: double var = x.xx (00000000 11111111 22222222 33333333) byte new0 = 0xFF (00000000) byte new1 = 0xFF (11111111) byte new2 = 0xFF (22222222) byte new3 = 0xFF (33333333)

The bytes are eventually going to end up in LabVIEW (Via XBEE Packets) in which I will reconstruct the bytes as a double.

Any help with this will be much appreciated.

Good luck, but you can use a union.

union pick_a_part { float a; byte b[4]} val;

val.a = float_val; byte b1 = val.b[0];

...

Frankly, I would just send text. No endian issues, et al.

I haven’t tested it, but here’s what I’ve come up with:

``````float f = 3.14159; // or whatever
// Caution:
// In the process of conversion, the original float will be destroyed.
// This code does not support infinities, NANs, or denormal numbers.
uint8_t top=0, second=0, third=0, bottom=0;
if (f < 0.0) {
top=128; // set negative flag
f=-f; // make positive
}
if (f > 0.0) {
top+=67;
while (f>=512.0) {
top++; // increase exponent by 2
f*=0.25; // divide float by 4
}
while (f<128.0) {
top--; // decrease exponent by 2
f*=4.0; // multiply float by 4
}
if (f<256.0) {
// float is in range 128.0 to 255.9999...
// so, low bit of exponent should be 0
second = (uint8_t)f; // integer part of float
f-=second; // fractional part of float
second-=128; // clear low bit of exponent
}
else {
// for floats 256.0 to 511.9999...
f*=0.5; // scale float to range 128.0 to 255.9999...
second = (uint8_t)f; // integer part of float
// high bit of exponent is now 1, which is how we want it
f-=second; // fractional part of float
}
// the last two bytes are straightforward
f*=256.0;
third=(uint8_t)f;
f-=third;
f*=256.0;
bottom=(uint8_t)f;
}
// we're done!
``````

The bytes are eventually going to end up in LabVIEW (Via XBEE Packets) in which I will reconstruct the bytes as a double

The type “double” in LabVIEW is 64 bits (8 bytes).

Another reason to go with ASCII.

check playground - http://playground.arduino.cc/Main/IEEE754tools