Android Question Convert byte array to single precision float

piedy

Member
Licensed User
Longtime User
Hi All,

I need some help. For the last couple of evenings I have been trying (unsuccessfully) to convert a byte array to a single precision point floating number. I believe I can use the byteconverter library but cannot get it working. Any chance of someone pointing me in the right direction?

Very many thanks.
 

stevel05

Expert
Licensed User
Longtime User
I just tried with ByteConverter and can see where the confusion is. ByteConverter will literally convert 4 consecutive bytes into a float. Whereas I assume that you want to fill the new array with the values stored in in the byte array.

You can just create a new array of the required type with the size of the original and copy the contents. The type will be taken care of.

It may be better to use type Double, see this thread. So:

B4X:
Dim DoubleArray(ByteArray.Length) As Double

For i = 0 to byteArray.Length-1
    DoubleArray(i)=ByteArray(i)
Next

The stored precision will be whatever is appropriate to the number, you will need to use NumberFormat to display the required output precision.

The other thing to remember is that bytes are signed.
 
Last edited:
Upvote 0

piedy

Member
Licensed User
Longtime User
I just tried with ByteConverter and can see where the confusion is. ByteConverter will literally convert 4 consecutive bytes into a float. Whereas I assume that you want to fill the new array with the values stored in in the byte array.

You can just create a new array of the required type with the size of the original and copy the contents. The type will be taken care of.

It may be better to use type Double, see this thread. So:

B4X:
Dim DoubleArray(ByteArray.Length) As Double

For i = 0 to byteArray.Length-1
    DoubleArray(i)=ByteArray(i)
Next

The stored precision will be whatever is appropriate to the number, you will need to use NumberFormat to display the required output precision.

The other thing to remember is that bytes are signed.

Many thanks for your help. Much appreciated. I'll give a whirl.
 
Upvote 0
Top