1

I am implementing a C function unsigned invert(unsigned x, int p, int n) that is returning x with the n bits that begin at position p inverted, leaving the others unchanged.

#include <stdio.h>

unsigned invert(unsigned x, int p, int n);

int main()
{
    printf("%u\n", invert(11111111, 5, 4));
    printf("%u\n", invert(10, 2, 2));

    return 0;
}

unsigned invert(unsigned x, int p, int n)
{   
    return x^(~(~0<<n)<<p+1-n);
}

This is what I got so far and if I'm tracing the function through it should be right, but I keep getting 11111163 for the first test and 12 for the second test.

Lundin
  • 195,001
  • 40
  • 254
  • 396
ganlaw
  • 1,303
  • 4
  • 18
  • 32
  • Explain the logic behind your function please (in the process, you'll probably figure out where you're wrong) – Luchian Grigore Sep 17 '12 at 13:14
  • 1
    are 11111111 and 10 supposed to be binary? I'm pretty sure c doesn't support binary literals... try 0xFF and 0x2 for those numbers. – Woodrow Douglass Sep 17 '12 at 13:16
  • `11111111` is a decimal integer, not binary. You need to pass in a hex value and convert that. Like `0xFF` (11111111 in binary) – Tony The Lion Sep 17 '12 at 13:17
  • `11111111` is not a binary value - it is a decimal value. There are no binary literals in C. The closest you'd get is either octal (eg. `0377`) or hexadecimal (eg. `0xFF`). Furthermore, bit positions (as in what `p` supposedly signifies) are usually counted from the right (or least significant) bit, which is at position 0. – Sander De Dycker Sep 17 '12 at 13:20

1 Answers1

2

I think your program is working. Only thing you have to do is express the number in binary.

unsigned invert(unsigned x, int p, int n); 

int main()
{
    printf("%x\n", invert(0b11111111, 5, 4));
    printf("%x\n", invert(0b10, 2, 2));

return 0;

}

unsigned invert(unsigned x, int p, int n)

{   
     return x^(~(~0<<n)<<p+1-n);
}

Is this what you want?

jpinto3912
  • 1,457
  • 2
  • 12
  • 19
Raj
  • 3,300
  • 8
  • 39
  • 67
  • this helps, but is there a way to return an binary number? – ganlaw Sep 17 '12 at 13:44
  • 1
    a number is a number. it depends on how you print it on the screen. If you want to print it in a binary format, you need something like [this](http://stackoverflow.com/questions/111928/is-there-a-printf-converter-to-print-in-binary-format) – Raj Sep 17 '12 at 13:51