I am trying to create a bitmap of 100 1s and 0s.
Below is what i came out so far.. I having issue printing the bitmap or rather i do not know how to print the bitmap.
I want to display the bitmap that consist of all the 1 and 0 that i had set. for index 0 to 99
int main()
{
unsigned int bit_position, setOrUnsetBit, ch;
unsigned char bit_Map_array_index, shift_index;
unsigned char bit_map[100] = { 0 };
do
{
printf("Enter the Bit position (bit starts from 1 and Ends at 100) \n");
scanf("%d", &bit_position);
printf(" Do you want to set/unset the Bit (1 or 0) \n");
scanf("%d", &setOrUnsetBit);
bit_Map_array_index = (bit_position - 1) / 8;
shift_index = (bit_position - 1) % 8;
printf("The bit_position : %d shift Index : %d\n", bit_position, shift_index);
if (setOrUnsetBit)
{
bit_map[bit_Map_array_index] |= 1 << shift_index; //set 1
}
else
{
bit_map[bit_Map_array_index] &= ~(1 << shift_index); //set 0
}
printf(" Do You want to Continue then Enter any Number"
"and for Exit then enter 100\n");
scanf("%d", &ch);
} while (ch != 100);
//I wan to print bitmap here after exiting
system("pause");
return 0;
}
I have very little experience in C programming... So correct me wherever i am wrong.
Thanks in advance.
You are working with bytes, not bits. You have 100 bytes, set each byte to 0 or 1. There is no need for shifting values:
unsigned char bytes[100];
for(int i = 0; i < sizeof(bytes); i++)
bytes[i] = rand() % 2;
for(int y = 0; y < 10; y++)
{
for(int x = 0; x < 10; x++)
{
int i = y * 10 + x;
printf("%d ", bytes[i]);
}
printf("\n");
}
If you are working with bits, then you can use
unsigned char data[13];
Because 13
is 13 * 8
bits, or 104
bits. You only need 100
bits. How you set and get the bits, depends on the format you choose. A bitmap file, for example, is padded so each line is multiple of 4-bytes. In general you can set the values as:
if(bytes[i])
data[byteindex] |= (1 << shift);
else
data[byteindex] &= ~(1 << shift);
To get the value back:
int value = (data[byte] & shift) > 0;