How do I convert an array of floats to a byte[] and back?
If you're looking for performance then you could use Buffer.BlockCopy
. Nice and simple, and probably about as fast as you'll get in managed code.
var floatArray1 = new float[] { 123.45f, 123f, 45f, 1.2f, 34.5f };
// create a byte array and copy the floats into it...
var byteArray = new byte[floatArray1.Length * 4];
Buffer.BlockCopy(floatArray1, 0, byteArray, 0, byteArray.Length);
// create a second float array and copy the bytes into it...
var floatArray2 = new float[byteArray.Length / 4];
Buffer.BlockCopy(byteArray, 0, floatArray2, 0, byteArray.Length);
// do we have the same sequence of floats that we started with?
Console.WriteLine(floatArray1.SequenceEqual(floatArray2)); // True
Convert float[] to byte[] to float[] again
I think you want to make use of the ByteBuffer
class, which has putFloat
and getFloat
methods.
How to convert an ContiguousArray of Floats into a byte array in Swift?
You can use the withUnsafeBytes()
method to get a buffer pointer to the underlying bytes of the array's contiguous storage, and directly initialize an [UInt8]
array from that buffer pointer. Example:
let floatArray: [Float] = [1.0, 2.0]
// Works also with a ContiguousArray:
// let floatArray: ContiguousArray<Float> = [1.0, 2.0]
let byteArray = floatArray.withUnsafeBytes { Array($0) }
print(byteArray) // [0, 0, 128, 63, 0, 0, 0, 64]
Equivalently (based on Leo's suggestion):
let byteArray = floatArray.withUnsafeBytes(Array.init)
The byte array contains the binary representation of the floating point numbers in host byte order (which is little-endian on all current Apple platforms). A conversion to big-endian is possible, but not without an intermediate copy to an integer array:
let floatArray: ContiguousArray<Float> = [1.0, 2.0]
let intArray = floatArray.map { $0.bitPattern.bigEndian }
let byteArray = intArray.withUnsafeBytes(Array.init)
print(byteArray) // 63, 128, 0, 0, 64, 0, 0, 0]
Reverse conversion: A simple method would be
let floatArray2 = byteArray.withUnsafeBytes { Array($0.bindMemory(to: Float.self)) }
print(floatArray2) // [1.0, 2.0]
However, that requires that the element storage of the byte array is properly aligned for floating point numbers. If that is not guaranteed then you can do
var floatArray2 = [Float](repeating: 0.0, count: byteArray.count / MemoryLayout<Float>.stride)
_ = floatArray2.withUnsafeMutableBytes { byteArray.copyBytes(to: $0) }
print(floatArray2) // [1.0, 2.0]
How to convert a float array to byte array in c#?
Try following :
float[] myArray = {0.0f, 0.0f, 0.0f};
int len = myArray.Length;
List<byte> bytes = new List<byte>();
foreach (float f in myArray)
{
byte[] t = System.BitConverter.GetBytes(f);
bytes.AddRange(t);
}
byte[] byteArray = bytes.ToArray();
How to Convert a float array to a byte[2] array and back java
To convert byte array to float array, what you are doing does not consider the endianness.
int myInt = (byte[0] << 24) |
((byte[1] & 0xff) << 16) |
((byte[2] & 0xff) << 8) |
(byte[3] & 0xff);
or (for little-endian):
int myInt = (byte[3] << 24) |
((byte[2] & 0xff) << 16) |
((byte[1] & 0xff) << 8) |
(byte[0] & 0xff);
Then you can transform to a float using this:
float asFloat = Float.intBitsToFloat(asInt);
To convert it back to byte array
int j=0;
byte[] byteArray=new byte[4];
int data=Float.floatToIntBits(asFloat);
byteArray[j++]=(byte)(data>>>24);
byteArray[j++]=(byte)(data>>>16);
byteArray[j++]=(byte)(data>>>8);
byteArray[j++]=(byte)(data>>>0);
I also find some similar information here
How to convert a byte array to float in Python
Apparently the Scala code that encodes the value uses a different byte order than the Python code that decodes it.
Make sure you use the same byte order (endianness) in both programs.
In Python, you can change the byte order used to decode the value by using >f
or <f
instead of f
. See https://docs.python.org/3/library/struct.html#struct-alignment.
>>> b = b'\xc2\xdatZ'
>>> struct.unpack('f', b) # native byte order (little-endian on my machine)
(1.7230105268977664e+16,)
>>> struct.unpack('>f', b) # big-endian
(-109.22724914550781,)
C Function to Convert float to byte array
Easiest is to make a union:
#include <stdio.h>
int main(void) {
int ii;
union {
float a;
unsigned char bytes[4];
} thing;
thing.a = 1.234;
for (ii=0; ii<4; ii++)
printf ("byte %d is %02x\n", ii, thing.bytes[ii]);
return 0;
}
Output:
byte 0 is b6
byte 1 is f3
byte 2 is 9d
byte 3 is 3f
Note - there is no guarantee about the byte order… it depends on your machine architecture.
To get your function to work, do this:
void float2Bytes(byte bytes_temp[4],float float_variable){
union {
float a;
unsigned char bytes[4];
} thing;
thing.a = float_variable;
memcpy(bytes_temp, thing.bytes, 4);
}
Or to really hack it:
void float2Bytes(byte bytes_temp[4],float float_variable){
memcpy(bytes_temp, (unsigned char*) (&float_variable), 4);
}
Note - in either case I make sure to copy the data to the location given as the input parameter. This is crucial, as local variables will not exist after you return (although you could declare them static
, but let's not teach you bad habits. What if the function gets called again…)
Converting a float to bytearray
It depends what you want, and what you are going to do with it. If all you want is a bytearray then:
import struct
value = 5.1
ba = bytearray(struct.pack("f", value))
Where ba
is a bytearray. However, if you wish to display the hex values (which I suspect), then:
print([ "0x%02x" % b for b in ba ])
EDIT:
This gives (for value 5.1):
['0x33', '0x33', '0xa3', '0x40']
However, CPython uses the C type double
to store even small floats (there are good reasons for that), so:
value = 5.1
ba = bytearray(struct.pack("d", value))
print([ "0x%02x" % b for b in ba ])
Gives:
['0x66', '0x66', '0x66', '0x66', '0x66', '0x66', '0x14', '0x40']
Related Topics
Entity Framework - Stored Procedure Return Value
Share Session Between Two Web Sites Using ASP.NET and State Server
The Connection Was Not Closed the Connection's Current State Is Open
System.Drawing in Windows or ASP.NET Services
How to Create an Instance from a String in C#
Regex Word Boundary Expressions
Can You Prevent Your ASP.NET Application from Shutting Down
Edit Raw Pixel Data of Writeablebitmap
Read from a File Starting at the End, Similar to Tail
Exporting Datagridview to CSV File
How to Serialize/Deserialize Simple Classes to Xml and Back
MVC 4 How Pass Data Correctly from Controller to View
How to Split an Ienumerable<String> into Groups of Ienumerable<String>