为 NSData iOS 中的每一位设置数据 [英] Set data for each bit in NSData iOS

查看:74
本文介绍了为 NSData iOS 中的每一位设置数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了长度为 2 个字节(16 位)的 NSData,我想将前 12 位设置为 (int)120 的二进制值,将第 13 位设置为 0 或 1(位),将第 14 位设置为 0 或 1(位)第 15 位为 0 或 1(位).

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

预期输出 => 0000 0111 1000 1011:最终二进制并将其转换为 NSData.

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.

推荐答案

这是您可能需要的确切代码:

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]);

输出: <078b>//x= 0000 0111 1000 1011//对于大端:<8b07> x= 1000 1011 0000 0111

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

这篇关于为 NSData iOS 中的每一位设置数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆