Search code examples
iosobjective-cnsdata

Set data for each bit in NSData iOS


I created NSData of length 2 bytes (16 bits) and I want to set first 12 bits as binary value of (int)120 and 13th bit as 0 or 1(bit), 14th bit as 0 or 1 (bit) and 15th bit as 0 or 1(bit).

    This is what I want to do:
             0000 0111 1000 --> 12 bits as 120 (int)
             1 <-- 13th bit 
             0 <-- 14th bit
             1 <-- 15th bit
             1 <-- 16th bit

Expected output => 0000 0111 1000 1011 : final binary and convert it to NSData.

How can I do that? Please give me some advice. Thanks all.


Solution

  • This is the exact code you might need:

    uint16_t x= 120; //2 byte unsigned int (0000 0000 0111 1000)
    //You need 13th bit to be 1
    x<<=1; //Shift bits to left .(x= 0000 0000 1111 0000)
    x|=1; //OR with 1 (x= 0000 0000 1111 0001)
    //14th bit to be 0.
    x<<=1; // (x=0000 0001 1110 0010)
    //15th bit to be 1
    x<<=1; //x= 0000 0011 1100 0100
    x|=1;  //x= 0000 0011 1100 0101
    //16th bit to be 1
    x<<=1; //x= 0000 0111 1000 1010
    x|=1;  //x= 0000 0111 1000 1011
    
    //Now convert x into NSData
    /** **** Replace this for Big Endian ***************/
    NSMutableData *data = [[NSMutableData alloc] init];
    int MSB = x/256;
    int LSB = x%256;
    [data appendBytes:&MSB length:1];
    [data appendBytes:&LSB length:1];
    
    /** **** Replace upto here.. :) ***************/
    //replace with : 
    //NSMutableData *data = [[NSMutableData alloc] initWithBytes:&x length:sizeof(x)];
    NSLog(@"%@",[data description]);
    

    Output: <078b> //x= 0000 0111 1000 1011 //for Big Endian : <8b07> x= 1000 1011 0000 0111