How to get a

Status
Not open for further replies.

kammateo

Member
Hi everyone,

I have a int number (17) and a float number (15.5) stored on a bin file. I want to print those numbers in a Serial Monitor. I can get the Integer number but not the Float number.

Code:
byte b[] = loadBytes(gFilename);

float x=0;
x= b[0];
println(x);

x= b[1];
println(x);

In the console I get:
17.0
0.0

I tried some operations without success:
Code:
x =(b[0] << 12);
x =(b[1] << 12) | (b[2] << 8) | (b[3] << 4) | (b[5] << 0);

Any ideas?
Thank you so much!!!!!
 
Usually this sort of thing is done with a union (the safe way), or by typecasting pointers (the dangerous way).

Here's how using a union.

Code:
void setup() {
  union {
    float f;
    byte b[4];
  } myvar;
  
  while (!Serial) {
    // wait for serial monitor
  }
  myvar.b[0] = 0;
  myvar.b[1] = 0;
  myvar.b[2] = 120;
  myvar.b[3] = 65;
  Serial.println("as float:");
  Serial.println(myvar.f);
  Serial.println("as bytes:");
  Serial.println(myvar.b[0]);
  Serial.println(myvar.b[1]);
  Serial.println(myvar.b[2]);
  Serial.println(myvar.b[3]);
}

void loop() {
  // put your main code here, to run repeatedly:

}
 
Status
Not open for further replies.
Back
Top