replace byte in 32 bit number

c

Solution

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 << (n << 3));
    int mask = 0xff << shift; // mask = 0xff << (n << 3)
    return (~mask & x) | shift;
}

int main ()
{
    printf("%X",replaceByte(0x80000000,0,0));

    return 0;
}

Problem

I have a function called `replaceByte(x,n,c)` that is to replace byte `n` in `x` with `c` with the following restrictions: - Bytes numbered from 0 (LSB) to 3 (MSB) - Examples: `replaceByte(0x12345678,1,0xab) = 0x1234ab78` - You can assume 0 <= n <= 3 and 0 <= c <= 255 - Legal ops: `! ~ & ^ | + << >>` Max ops: 10 ``` int replaceByte(int x, int n, int c) { int shift = (c << (8 * n)); int mask = 0xff << shift; return (mask & x) | shift; } ``` but when I test it I get this error: ERROR: Test replaceByte(-2147483648[0x80000000],0[0x0],0[0x0]) failed... ...Gives 0[0x0]. Should be -2147483648[0x80000000] after realizing that * is not a legal operator I have finally figured it out...and if you are curious, this is what I did: ``` int replaceByte(int x, int n, int c) { int mask = 0xff << (n << 3); int shift = (c << (n << 3)); return (~mask & x) | shift; } ```

Original source