Replace byte with 32-bit number

I have a function called replaceByte(x,n,c) , which will replace bytes n to x in the c with the following restrictions:

  • Bytes numbered 0 (LSB) to 3 (MSB)
  • Examples: replaceByte(0x12345678,1,0xab) = 0x1234ab78
  • You can take 0 <= n <= 3 and 0 <= c <= 255
  • Legal operations ! ~ & ^ | + << >> ! ~ & ^ | + << >>
  • 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]. Must be -2147483648 [0x80000000]

after realizing that * is not a legal operator, I finally figured it out ... and if you're interested, 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; } 
+6
source share
3 answers

Ah ... you're almost there.

Just change

 return (mask & x) | shift; 

to

 return (~mask & x) | shift; 

mask should contain everything except the area to be masked, and not vice versa.

I use 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; } 
+4
source

Since this looks like homework, I am not going to send the code, but I list the steps you need to follow:

  • Insert c into a 32-bit number so you don't lose any bits when moving
  • Then shift c by the corresponding number of bits to the left (if n==0 there is no bias, if n==1 shift by 8, etc.)
  • Create a 32-bit bitmask that will zero the least 8 bits of x , and then shift that mask by the same amount as in the last step
  • Perform bitwise AND of the offset bitmask and x to reset the corresponding bits of x
  • Perform a bitwise OR (or append) of the shifted value of c and x to replace the masked bits of the last
+6
source

The correct solution is also for c = 0:

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

Source: https://habr.com/ru/post/913085/


All Articles