0

I have a char[16] array and i'm getting input from the user: Input for example- 15, 21 ,23, -1

I need to set the bit value to '1' for the place 15,21 and 23. -1 will finish the program.

Every char[16] array represent values from 0-127, that represents bits. I'm having problem entering '1' into 15,21 and 23 cells.

Here is my program

int temp;
char A[16];
/*Sets all the cells values to o*/
memset(A, 0, 16*sizeof(char));
While (int != -1)
{
    scanf("Enter values from the user:%d", val");
    div = (temp/8);
    mod = (temp%8);
    A[div] |= (mod<<=1);
}

The problem that it's not setting cell 15,21 and 23 values to '1'.

3
  • 7
    <<= is not the same as <<. Jun 10, 2012 at 18:47
  • 3
    Also, you haven't posted your actual code. Please post your actual code. Jun 10, 2012 at 18:48
  • Does it set any other cell to 1? Or does it fail to set anything at all?
    – anatolyg
    Jun 10, 2012 at 18:54

2 Answers 2

2

Use this to set the right bit:

A[div] |= (1<<mod);

Related question: How do you set, clear, and toggle a single bit?

Full code example:

#include <iostream>

int main() {
    unsigned char A[16];
    memset(A, 0, sizeof(A));
    int t;
    std::cin >> t;
    while (t != -1)
    {
        int div = (t/8);
        int mod = (t%8);
        A[div] |= (1<<mod);
        std::cin >> t;
    }
    for(int i = 0; i < 16; ++i) {
        std::cout << (int)A[i] << " ";
    }
    std::cout << std::endl;
    return 0;
}
4
  • A[div] |= (1<<mod); returns the value 16
    – judith
    Jun 10, 2012 at 19:24
  • And what value it should return?
    – user243901
    Jun 10, 2012 at 19:32
  • I'm trying to set the bit to 1
    – judith
    Jun 10, 2012 at 19:35
  • I posted the actual code, on which input data it gives wrong answer?
    – user243901
    Jun 10, 2012 at 19:38
0

bit-fields are not defined for char(if u use char use unsigned.. ) , use unsigned int. Or the C99 boolean type. https://stackoverflow.com/a/3971334/1419494

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.