简体   繁体   English

如何将两位加到十六进制中

[英]how to add two bits into a hex

I have two bytes and I am setting different bits in order to get different combinations. 我有两个字节,并且我设置了不同的位以获取不同的组合。 Eg, byte 1 bit 7 and byte 2 bit 1,bit 2 makes a combination device ready. 例如,字节1的第7位和字节2的第1位,第2位使组合设备就绪。 Now, I have created mask 现在,我创建了面具

#define C1_device_ready   (0x80 | 0x100 | 0x200)

Then I read the data and try to compare. 然后,我读取了数据并尝试进行比较。 for 1 byte I can do (data[0] & mask == mask). 我可以做1个字节(data [0]&mask == mask)。 But how can I compute it for C1_device_ready mask where there are two bytes, data[0] and data[1]. 但是,如何为有两个字节的data_0和data [1]的C1_device_ready掩码计算它。 Is it easily possible or should I do masking only in single byte. 是否容易做到?还是只应在单个字节中进行屏蔽? ::added::data is unsigned char data[2] :: added :: data是未签名的char数据[2]

If data is an array of unsigned char , you could test 如果data是一个unsigned char数组,则可以测试

if ((data[0] & mask) == (mask & 0xFF) && (data[1] & mask) == ((mask >> 8) & 0xFF))

or combine the two data[i] and check 或合并两个data[i]并检查

if (((data[0] | (data[1] << 8)) & mask) == mask)

Use 采用

if (((data[0] | (data[1] << 8)) & mask) == mask) {
    // do something
}
((data[0] | (data[1]<<8)) & mask) == mask

should work. 应该管用。 Might need to cast things as unsigned int 可能需要将事物强制转换为unsigned int

尝试:

if ((*(short *)data) & C1_device_ready)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM