views:

102

answers:

3

Hello all,

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  A: 

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

Brian R. Bondy
+2  A: 

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.

Alexandre C.
Mike Seymour
wouldn't name a variable byte
Oops
@Mike Seymour : You're right, I edit the answer.
Alexandre C.
There are a couple of mistakes in the above code - you need a `~` in front of the byte masks.
Paul R
@Paul R: Are you sure ?
Alexandre C.
I'd always go with a function instead of a macro where possible!
AshleysBrain
@Alexandre C.: OK - it looks someone else fixed it for you in a different way now
Paul R
oh ok so thanks caf
Alexandre C.
This works really well, actually, but I found I had to make sure byte=0 before I started because my compiler was filling it with garbage.
CrypticPrime
A: 

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;
DanDan
a union with one member is not worth being a union...
Alexandre C.
It's a pseudo union to reinforce a concept. I'd prefer it to a couple of buggy macros.
DanDan
I prefer inline functions to both macros and pseudo unions. ;-)
Peter G.