Reputation: 825
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'.
Upvotes: 0
Views: 2755
Reputation:
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;
}
Upvotes: 2
Reputation: 976
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
Upvotes: 0