0

I need to convert a 32 bit floating point number to 4 bytes for an embedded system using the Squirrel language. I was hoping I could just bit shift and mask the bytes into separate parts, doing something like:

bytes = [
    (myfloat >> 24) & 0xff,
    (myfloat >> 16) & 0xff,
    (myfloat >>  8) & 0xff,
    (myfloat      ) & 0xff,
]

However, this gives me a type error saying that you can't bit shift on a float.

The only other thing I see in the docs is the tointeger function, so I could cast to an integer and then get the nondecimal part, but even then I will also need to go the other way from bytes to a float later.

Any ideas?

Nakilon
  • 34,866
  • 14
  • 107
  • 142
davidscolgan
  • 7,508
  • 9
  • 59
  • 78

1 Answers1

0

Aha, you have to read and write the float value to a blob:

local pi = 3.1415926;
bl <- blob(4);
bl.writen(pi, 'f');
bytes <- [];
foreach (byte in bl) {
    server.log(byte);
    bytes.append(byte);
}
back <- blob(4);
foreach (byte in bytes) {
    back.writen(byte, 'b');
}
back.seek(0, 'b');
server.log(back.readn('f'));
davidscolgan
  • 7,508
  • 9
  • 59
  • 78
  • Are you trying to write the integer value of the float over several bytes, or are you trying to store the binary encoding of the float (as a float) in a series of bytes? The question looks like the former (minus a cast), your answer looks like the latter. – Chris Stratton Oct 02 '13 at 14:02
  • The latter is what I was shooting for. – davidscolgan Oct 02 '13 at 21:08