获取字节流中的颜色值

时间:2013-02-14 17:27:06

标签: ios objective-c nsdata

我从二进制文件(.ase)读取此字节流粗体值表示颜色:

&LT; 41534546 00010000 00000005 c0010000 00140008 004f0070 0061006c 0074006f 006e0065 00000001 00000024 00080023 00320042 00420034 00300046 00005247 4220 * 3e2c acad3f34 b4b53d70 F0F1 * 0002 00010000 00240008 00230046 00460035 00420033 00310000 52474220的 3f800000 3eb6b6b7 3e44c4c5 < / strong> 00020001 00000024 00080023 00460046 00380037 00340038 00005247 4220 * 3f80 00003f07 87883e90 9091 * 0002 00010000 00240008 00230030 00330038 00340043 00410000 52474220 3c40c0c1 3f048485 3f4acacb 0002&gt;

如果颜色为9BD6AE,那么字节块将 3f1b9b9c 3f56d6d7 3f2eaeaf

每个块表示每个颜色分量的浮点值。 (红色:0.607843绿色:0.839216蓝色:0.682353)

如何从上述数据流中获取这些浮点值?

1 个答案:

答案 0 :(得分:0)

假设您拥有包含文件内容的NSData,您可以使用以下代码将这些值转换为float

NSData *data = ... // contents of the ASE file
const void *bytes = [data bytes];
int offset = ... // offset into the data stream (in bytes)

// assuming offset is pointing to the start of 4 bytes that represent a float value:
float colorComponent = [self floatFromBytes:bytes + offset];


// Helper method to convert bytes to a float
// In ASE file, float values are 4-byte values in big-endian format
- (float)floatFromBytes:(const void *)bytes {
    uint_32_t beVal = *(uint_32_t *)bytes; // data is in big-endian format
    uint_32_t locVal = CFSwapInt32BigToHost(beVal); // data in host format

    float res = *(float *)&locVal; // convert bytes to float

    return res;
}

这远非完整的ASE解析算法。但这显示了如何将4字节值转换为float值。您需要处理ASE文件格式的许多其他方面。