replace byte in 32 bit number

Since this looks like homework I'm not going to post code, but list the steps you need to perform:

  1. Cast c into a 32-bit number so you don't lose any bits while shifting
  2. Next, shift c by the appropriate number of bits to the left (if n==0 no shifting, if n==1 shift by 8 etc.)
  3. Create a 32-bit bitmask that will zero the lowest 8 bits of x, then shift this mask by the same amount as the last step
  4. Perform bitwise AND of the shifted bitmask and x to zero out the appropriate bits of x
  5. Perform bitwise OR (or addition) of the shifted c value and x to replace the masked bits of the latter

Proper solution is for c = 0 as well:

     int replaceByte(int x, int n, int c)
     {
        int shift = 8 * n;
        int value = c << shift;
        int mask = 0xff << shift;

        return (~mask & x) | value;
     }

Ahh... You are almost there.

Just change

return (mask & x) | shift; 

to

return (~mask & x) | shift;

The mask should contain all ones except for the region to be masked and not vice versa.

I am using this simple code and it works fine in gcc

#include<stdio.h>

int replaceByte(int x, int n, int c) 
{
    int shift = (c << (8 * n));
    int mask = 0xff << shift;
    return (~mask & x) | shift;
}

int main ()
{

    printf("%X",replaceByte(0x80000000,0,0));

    return 0;
}

Tags:

C