float to byte[4] to float without using BitConverter?
如何将浮点转换为字节数组,然后在不使用bitconverter的情况下将字节数组重新转换为浮点??
事先谢谢。
如果
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 | [StructLayout(LayoutKind.Explicit)] public struct UInt32ToSingle { [FieldOffset(0)] public uint UInt32; [FieldOffset(0)] public float Single; [FieldOffset(0)] public byte Byte0; [FieldOffset(1)] public byte Byte1; [FieldOffset(2)] public byte Byte2; [FieldOffset(3)] public byte Byte3; } public static float FromByteArray(byte[] arr, int ix = 0) { var uitos = new UInt32ToSingle { Byte0 = arr[ix], Byte1 = arr[ix + 1], Byte2 = arr[ix + 2], Byte3 = arr[ix + 3], }; return uitos.Single; } public static byte[] ToByteArray(float f) { byte[] arr = new byte[4]; ToByteArray(f, arr, 0); return arr; } public static void ToByteArray(float f, byte[] arr, int ix = 0) { var uitos = new UInt32ToSingle { Single = f }; arr[ix] = uitos.Byte0; arr[ix + 1] = uitos.Byte1; arr[ix + 2] = uitos.Byte2; arr[ix + 3] = uitos.Byte3; } |
注意,我对
使用实例:
1 2 | byte[] b = ToByteArray(1.234f); float f = FromByteArray(b); // 1.234f |