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:
- Cast
c
into a 32-bit number so you don't lose any bits while shifting - Next, shift
c
by the appropriate number of bits to the left (ifn==0
no shifting, ifn==1
shift by 8 etc.) - 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 - Perform bitwise AND of the shifted bitmask and
x
to zero out the appropriate bits ofx
- Perform bitwise OR (or addition) of the shifted
c
value andx
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;
}