Objective-C将2个字节转换为浮点数

时间:2016-08-19 08:52:59

标签: objective-c floating-point type-conversion byte

我有2个字节的温度值,如: [0x0C,0xDE]我需要将它转换为浮点数,我试图做的是:

NSData *payload <-- this contains the bytes in the "range" defined after
[payload getBytes:&bytes range:range];

float f;
int16_t bytes = OSSwapBigToHostInt16(bytes);
memcpy(&f, &bytes, 2);

NSLog(@"Value found: %f", f);

但我总是得到0.0000的值。

感谢。

3 个答案:

答案 0 :(得分:0)

我认为问题在于memcpy。


    // Set up the test data.
    char testBytes[2];
    testBytes[0] = 0x0C;
    testBytes[1] = 0xDE;

    // Create a demo payload.
    payload = [NSData dataWithBytes:&testBytes length:2];

    // Copy data into an int16.
    int16_t bytes;
    [payload getBytes:&bytes range:NSMakeRange(0, 2)];

    // Sort out endianess.
    bytes = OSSwapBigToHostInt16(bytes);

    // We now have an int16, so cast it to a float.
    float f = (float)bytes;

    NSLog(@"Value found: %f", f);  // 3294.0

我认为你不能将int16直接记入浮点数。从根本上说,它们有两种不同的二进制表示。一个人不是简单地走进浮点:)。但是,你可以投。

答案 1 :(得分:0)

我回到了这个问题。此代码适用于相同的值,如下所示:

给定有效载荷= 0x07c3

unsigned result = 0;
NSString *hexString = [payload hexadecimalString]; // 07:c3
hexString = [hexString stringByReplacingOccurrencesOfString:@":" withString:@""]; // 07c3

NSScanner *scanner = [NSScanner scannerWithString:hexString];
[scanner scanHexInt:&result];
value = ((float) result) / 100;

NSLog(@"Value found: %f", value); // 19.87

但是例如它不起作用:0c4e应返回22.04

因为我不期望Obj-c和十六进制转换,所以我们会感谢任何更好的代码。

答案 2 :(得分:0)

使用您自己答案中的值:

- (void)testTwoBytesToFloat {
   //0x07C3   1987
   Byte lowByte = 0xC3; //Big-Endian, if Small-Endian use: 0x07;
   Byte highByte = 0x07; //Big-Endian, if Small-Endian use: 0xC3;

    NSInteger n = (int)highByte << 8;
    n |= (int)lowByte;

    XCTAssertEqual(n, 1987, @"%ld", (long)n);

    float temp = [NSNumber numberWithInteger:n].floatValue / 100;
    XCTAssertEqualWithAccuracy(temp, 19.87, 2, @"%.2f", temp);
}