Set data for each bit in NSData iOS

纵然是瞬间 提交于 2019-12-25 06:57:57

问题


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.


回答1:


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




回答2:


0000011110001011 in bit is 0x07 0x8b in byte.

unsigned char a[2] ;
a[0] = 0x07 ;
a[1] = 0x8b ;
NSData * d = [NSData dataWithBytes:a length:2] ;



回答3:


Recently i wrote this code for my own project.. Check if this can be helpful to you.

//Create a NSMutableData with particular num of data bytes
NSMutableData *dataBytes= [[NSMutableData alloc] initWithLength:numberOfDataBytes];

//get the byte in which you want to change bit.
char x;
[dataBytes getBytes:&x range:NSMakeRange(bytePos,1)];
//change the bit here by shift operation
x |= 1<< (bitNum%8);
//put byte back in NSMutableData
[dataBytes replaceBytesInRange:NSMakeRange(bytePos,1) withBytes:&x length:1];

Let me know if you need more help ..:)

For changing 13th bit based on string equality

if([myString isEqualTo:@"hello"])
{
 char x;
    [dataBytes getBytes:&x range:NSMakeRange(0,1)];
    //change the bit here by shift operation
    x |= 1<< (4%8); // x |=1<<4;
    //put byte back in NSMutableData
    [dataBytes replaceBytesInRange:NSMakeRange(0,1) withBytes:&x length:1];
}


来源:https://stackoverflow.com/questions/20772161/set-data-for-each-bit-in-nsdata-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!