Search code examples
arraysobjective-cnsdatatcpsocket

How do I convert a 24-bit integer into a 3-byte array?


Hey Im totally out of my depth and my brain is starting to hurt.. :(

I need to covert an integer so that it will fit in a 3 byte array.(is that a 24bit int?) and then back again to send/receive this number from a byte stream through a socket

I have:

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

I guess my main problem is that I do not know how to check that I have indeed converted my int correctly which is the converting back that I need to do as well for sending the data.

Any help greatly appreciated!


Solution

  • You could use a union:

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

    to convert from int to bytes:

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

    to convert from bytes to int:

    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
    

    Note: using unions in this manner relies on processor byte-order. The example I gave will work on a little-endian system (like x86).