gpt4 book ai didi

ios - 如何将 4 个字节转换为来自 NSData 的 Objective-C 中的 float

转载 作者:行者123 更新时间:2023-12-01 18:11:21 25 4
gpt4 key购买 nike

这是一个在 Objective-c 中将 4 个字节转换为 32 位整数的示例。函数读取 中获取 4 个字节阅读 函数,然后将其转换为单个 32 位 int。有谁知道我如何将 4 个字节转换为浮点数?我相信它是大端。基本上我需要一个 readFloat 函数。我永远无法掌握这些按位运算。

编辑:
我忘了提到原始数据来自 Java 的 DataOutputStream 类。根据 java doc 的 writeFloat 函数是

Converts the float argument to an int using the floatToIntBits method in class Float, and then writes that int value to the underlying output stream as a 4-byte quantity, high byte first.



这是Objective c试图提取java写入的数据。
- (int32_t)read{
int8_t v;
[data getBytes:&v range:NSMakeRange(length,1)];
length++;
return ((int32_t)v & 0x0ff);
}

- (int32_t)readInt {
int32_t ch1 = [self read];
int32_t ch2 = [self read];
int32_t ch3 = [self read];
int32_t ch4 = [self read];
if ((ch1 | ch2 | ch3 | ch4) < 0){
@throw [NSException exceptionWithName:@"Exception" reason:@"EOFException" userInfo:nil];
}
return ((ch1 << 24) + (ch2 << 16) + (ch3 << 8) + (ch4 << 0));
}

最佳答案

OSByteOrder.h包含用于读取、写入和转换整数数据的函数。

您可以使用 OSSwapBigToHostInt32()将大端整数转换为 native 表示,然后将位复制到浮点数中:

    NSData* data = [NSData dataWithContentsOfFile:@"/tmp/java/test.dat"];

int32_t bytes;
[data getBytes:&bytes length:sizeof(bytes)];

bytes = OSSwapBigToHostInt32(bytes);

float number;
memcpy(&number, &bytes, sizeof(bytes));

NSLog(@"Float %f", number);

关于ios - 如何将 4 个字节转换为来自 NSData 的 Objective-C 中的 float ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30608669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com