1

Hi I have written a program to toggle bits in char array. I found that when I am toggling the 7th bit I am getting wrong answer. Please help me.

int main() {
    int n,c;
    char dummy;
    scanf("%i", &n);
    char a[13];
    memset(a,0x00,13);
    for(int a_i = 0; a_i < n; a_i++){
       scanf("%d",&c);
        dummy = c%8;
        a[c/8] ^= (1<<dummy);
    }
    printf("\n");
    for (int _i=0;_i<13;_i++)printf("%x ",a[_i]);
//    int result = lonelyinteger(n, a);
//    printf("%d\n", result);
    return 0;
}

Input:
9
4 9 95 93 57 4 57 93 9

Output:
0 0 0 0 0 0 0 0 0 0 0 **ffffff80** 0 

I need the output as 80 only not ffffff80. Please help me with this.

Damodharan_C
  • 313
  • 1
  • 2
  • 11

1 Answers1

-1

Remember that it is not only the signed-ness of the array type, but the signed-ness of the integer literal that you are shifting that matters. Make sure both are unsigned.

x ^= 1U << n;
Dúthomhas
  • 8,200
  • 2
  • 17
  • 39
  • 1
    This is good general advice; however `dummy` never exceeds `7` in OP's code, and there is no difference between `x ^= (1 << 7)` and `x ^= (1u << 7)`. The problem is more to do with the declared type of `x` – M.M Oct 11 '17 at 05:16