【问题标题】:How do I convert a 24-bit integer into a 3-byte array?如何将 24 位整数转换为 3 字节数组?
【发布时间】:2010-12-07 15:17:16
【问题描述】:

嘿,我完全超出了我的理解范围,我的大脑开始受伤了.. :(

我需要转换一个整数,使其适合 3 字节数组。(那是 24 位整数吗?)然后再次返回以通过套接字从字节流中发送/接收这个数字

我有:

NSMutableData* data = [NSMutableData data];

 int msg = 125;

 const void *bytes[3];

 bytes[0] = msg;
 bytes[1] = msg >> 8;
 bytes[2] = msg >> 16;

 [data appendBytes:bytes length:3];

 NSLog(@"rtn: %d", [[[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding] intValue]);

 //log brings back 0

我想我的主要问题是我不知道如何检查我是否确实正确地转换了我的 int,这也是我在发送数据时需要做的转换。

非常感谢任何帮助!

【问题讨论】:

    标签: arrays objective-c nsdata tcpsocket


    【解决方案1】:

    假设您有一个 32 位整数。您希望将底部的 24 位放入一个字节数组中:

    int msg = 125;
    byte* bytes = // allocated some way
    
    // Shift each byte into the low-order position and mask it off
    bytes[0] = msg & 0xff;
    bytes[1] = (msg >> 8) & 0xff;
    bytes[2] = (msg >> 16) & 0xff;
    

    将 3 个字节转换回整数:

    // Shift each byte to its proper position and OR it into the integer.
    int msg = ((int)bytes[2]) << 16;
    msg |= ((int)bytes[1]) << 8;
    msg |= bytes[0];
    

    而且,是的,我完全知道有更优化的方法来做到这一点。上面的目标是清晰。

    【讨论】:

    • 只要数字
    • @loststudent:不,24 位无符号整数的最大值是 (2^24)-1,或 16,777,216。带符号的 24 位 int 的范围是 -8,388,608 到 8,388,607。哪个部分不工作?
    • 就在 int 超过 255 的时候
    【解决方案2】:

    你可以使用联合:

    union convert {
        int i;
        unsigned char c[3];
    };
    

    从 int 转换为字节:

    union convert cvt;
    cvt.i = ...
    // now you can use cvt.c[0], cvt.c[1] & cvt.c[2]
    

    从字节转换为整数:

    union convert cvt;
    cvt.i = 0; // to clear the high byte
    cvt.c[0] = ...
    cvt.c[1] = ...
    cvt.c[2] = ...
    // now you can use cvt.i
    

    注意:以这种方式使用联合依赖于处理器字节顺序。我给出的示例适用于 little-endian 系统(如 x86)。

    【讨论】:

      【解决方案3】:

      来点指针技巧怎么样?

      int foo = 1 + 2*256 + 3*65536;
      const char *bytes = (const char*) &foo;
      printf("%i %i %i\n", bytes[0], bytes[1], bytes[2]); // 1 2 3
      

      如果您要在生产代码中使用它,可能需要注意一些事情,但基本思想是理智的。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-07-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2018-11-19
        相关资源
        最近更新 更多