Collectives™ on Stack Overflow
Find centralized, trusted content and collaborate around the technologies you use most.
Learn more about Collectives
Teams
Q&A for work
Connect and share knowledge within a single location that is structured and easy to search.
Learn more about Teams
I am working on a project where I have to read data from device and then convert it in byte array and then read some bytes(4 byte) and convert them in float and use it. I have code that is working fine but in android but I am unable to convert the code correctly. Here is the android code
try {
byte[] data = Arrays.copyOfRange(mScanRecord, 5, 9); //mScanRecord is byte array (byte[]) containing 11 byte
searchModel.setData("" + ByteBuffer.wrap(data).getFloat());
} catch (Exception e) {
e.printStackTrace();
searchModel.setData("" + 0);
And here is the code that I converted in swift
typealias Byte = UInt8
func fromByteArray<T>(_ value: [UInt8], _: T.Type) -> T {
return value.withUnsafeBytes {
$0.baseAddress!.load(as: T.self)
func getUnitValue(byteArray:[UInt8]) -> Float {
let value = fromByteArray([byteArray[7], byteArray[8], byteArray[9], byteArray[10]], Float.self)
return value
..... In Some function I call .....
searchModel.setData(data: String(format: "%.10f", getUnitValue(byteArray: byteArray)))
It is giving me value but value is very different from android
I am expecting value around
2.0405695(like in android)
2.0405587
2.0526589
but I am getting
547669365842.0000
-652321236542.0000
0.000000103
value changes every few seconds in both device
In iOS
Printing description of byteArray:
▿ 13 elements
- 0 : 195
- 1 : 4
- 2 : 1
- 3 : 213
- 4 : 130
- 5 : 0
- 6 : 0
- 7 : 64
- 8 : 2
- 9 : 152
- 10 : 178
- 11 : 213
- 12 : 130
In Android
Values looks different but these are same if convert them to decimal to hex
–
–
The byte array contains the big endian representation of a 32-bit
floating point value. You have to convert that to the host byte order
(which is little-endian on all current Apple platforms):
func getUnitValue(byteArray:[UInt8]) -> Float {
let value = fromByteArray([byteArray[7], byteArray[8], byteArray[9], byteArray[10]], UInt32.self)
return Float(bitPattern: UInt32(bigEndian: value))
let array: [UInt8] = [195, 4, 1, 213, 130, 0, 0, 64, 2, 152, 178, 213, 130]
print(getUnitValue(byteArray: array)) // 2.0405587
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.