I have a byte array sent via UDP from x-plane. The bytes (4) are all floats or integers…
I tried to cast them to floats but no luck so far…
Example array:
byte data[41] = {-66,30,73,0};
How do I convert 4 bytes into int or float and doesn’t float use 8 bytes?
Note: I recommend @Ophidian’s
ByteBufferapproach below, it’s much cleaner than this. However this answer can be helpful in understanding the bit arithmetic going on.I don’t know the endianness of your data. You basically need to get the bytes into an int type depending on the order of the bytes, e.g.:
Then you can transform to a float using this:
This is basically what
DataInputStreamdoes under the covers, but it assumes your bytes are in a certain order.Edit – On Bitwise OR
The OP asked for clarification on what bitwise OR does in this case. While this is a larger topic that might be better researched independently, I’ll give a quick brief. Or (
|) is a bitwise operator whose result is the set of bits by individually or-ing each bit from the two operands.E.g. (in binary)
When I suggest using it above, it involves shifting each byte into a unique position in the int. So if you had the bytes
{0x01, 0x02, 0x03, 0x04}, which in binary is{00000001, 00000010, 00000011, 00000100}, you have this:When you OR two numbers together and you know that no two corresponding bits are set in both (as is the case here), bitwise OR is the same as addition.
See Also