Storing a nibble (4 bits) at a memory location

2 days and no results. What I am trying to do here is store 4 bits (representing decimal numbers 1 to 15) at an effective memory address. As such a byte in memory will contain 2 4-bits which I can then "decode" using logical and shifting operations. The latter part seems doable. But I just can't get the first part done. Is it even doable for that matter?
Your machine is almost certainly byte addressable, so you have to decide where in the byte you want to store the nibble and place it there using a mask, then write the byte into memory somewhere.
Yeah, but if I store a byte (whose left-most 4 bits are all masked to 0), there really is no way to get the right-most 4 bits of the next byte to overwrite those left-most 4 bits (all zeros) of the previous byte. I can only step through memory in bytes, right? Nothing less. If that is the case, then I think what I am trying to do is not doable.
Why not store the 4 bits in an array... int bit1[4]; then you can easily go through and do all those processes
When you want to store something in 4 bits, you're generally thinking of memory use, not ease of manipulation. So suggesting he takes what, on my system would be about 16 times the memory he was wanting to use, doesn't seem terribly productive.
Perhaps you need something bit like this:
1
2
3
4
void set_left_nibble(char* ptr, char nibble)
{
    *ptr = (*ptr & 0x0F) | (nibble & 0xF0);
}


It preserves the right nibble of the memory location by ANDing with 0x0F and then ORs the left nibble of the memory location with the left nibble of the parameter.
Last edited on
A similar project I did to this was to take decimal numbers, convert to binary do the operation at the same time and print out.. below is my code , not sure how much it helps but maybe it could do you some good.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
displayBinary ( num1 & num2 ) ;  // this is the operation type.. 

void displayBinary( int number )
{
     const int SHIFT = 8*sizeof( unsigned ) - 1;
     const unsigned MASK = 1 << SHIFT;
     
     std::cout << setw( 10 ) << number << " = ";
     
     //display bits
     for (unsigned i = 1; i <= SHIFT + 1; ++i )
     {
      std::cout << ( number & MASK ? '1' : '0' );
      number <<= 1; // shift values left by 1
      
      if ( i % 4 == 0 ) // output a space after 8 bits
        cout << ' ';    
     }      
     
     cout << endl;
}


you can send all the binary operations to this function and it works great :) just use a switch statement to get the char of the operation and pass it through, or manually type in your functions ...
Last edited on
Thank you oonej and everyone else for your input. I really appreciate it. I will give Galik's and oonej's methods a shot. But, overall, I can now address the problem in a better way thanks to you guys.
Topic archived. No new replies allowed.