Reading/Writing Nibbles (without bit fields) in C/C++

瘦欲@ 提交于 2019-12-07 17:47:03

问题


Is there an easy way to read/write a nibble in a byte without using bit fields? I'll always need to read both nibbles, but will need to write each nibble individually.

Thanks!


回答1:


Use masks :

char byte;
byte = (byte & 0xF0) | (nibble1 & 0xF); // write low quartet
byte = (byte & 0x0F) | ((nibble2 & 0xF) << 4); // write high quartet

You may want to put this inside macros.




回答2:


The smallest unit you can work with is a single byte. If you want to manage the bits you should use bitwise operators.




回答3:


You could create yourself a pseudo union for convenience:

union ByteNibbles
{
    ByteNibbles(BYTE hiNibble, BYTE loNibble)
    {
        data = loNibble;
        data |= hiNibble << 4;
    }

    BYTE data;
};

Use it like this:

ByteNibbles byteNibbles(0xA, 0xB);

BYTE data = byteNibbles.data;


来源:https://stackoverflow.com/questions/3110306/reading-writing-nibbles-without-bit-fields-in-c-c

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