hi...
let's say i got a char a = 'A';
and an arry of bool b[8];
how to convert variable a into binary and store it into b[]?
Thanks
Printable View
hi...
let's say i got a char a = 'A';
and an arry of bool b[8];
how to convert variable a into binary and store it into b[]?
Thanks
A for loop, and use of the >>(shift-right) and &(bitwise-and) operators
can you demostrate with some coding?
Code:#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
void printBits(unsigned long val){
int i, end = sizeof(unsigned long) * 8;
unsigned long tmp = (ULONG_MAX / 2) + 1;
for (i=0; i<end; i++){
if (tmp & val) putc('1', stdout);
else putc('0', stdout);
tmp >>= 1;
}
}
int main(){
int number = 0;
char buf[BUFSIZ];
while (1){
printf("Please enter a number to convert to binary: ");
fgets(buf, BUFSIZ, stdin);
rewind(stdin);
number = atoi(buf);
printBits(number);
printf("\n");
}
return 0;
}
For example:
num & 1 is true if the 1st bit is 1.
Of course if it isnt true, then the 1st bit is 0.
num = num >> 1 would then bitwise shift num such that the 2nd bit is now the 1st bit.
Excellent code, mitakeet. Except I don't see BUFSIZ declared anywhere. Or is it part of one of the header files?
ok.. my code:
ok... now how do we convert from bits back to the original variable value?Code:void main()
{
unsigned char a = 1;
unsigned char b[8];
char mask = 1;
int i;
for(i = 8; i > 0; i--)
{
printf("%d", a & mask);
b[i - 1] = a & mask;
a >>= 1;
}
printf("\n");
for(i = 0; i < 8; i++)
{
if(b[i] == 1)
{
printf("1");
}
else
{
printf("0");
}
}
}
BUFSIZ is declared in <stdio.h> and is typically around 512 bytes.
If you want to put it back together, you |= with the appropriate bit mask.
coding example please....
int value = 0;
int mask1 = 1;
value |= mask1;//now first (lowest order) bit is set
int mask2 = 2
value |= mask2;//now first and second low order bits are set
int mask3 = 4;....
based on my program the bits is store on b[8];
i try:
but not working......Code:void main()
{
unsigned char a = 'a';
unsigned char c = 0;
unsigned char b[8];
char mask = 1;
int i;
for(i = 8; i > 0; i--)
{
printf("%d", a & mask);
b[i - 1] = a & mask;
a >>= 1;
}
printf("\n");
for(i = 0; i < 8; i++)
{
c |= b[i];
c <<= 1;
if(b[i] == 1)
{
printf("1");
}
else
{
printf("0");
}
}
printf("\n%c\n", c);
}
What does it output?
output:
ThanksCode:
10000110
01100001
┬
01100001 is the ASCII code for 'a'.
yes... the binary ASCIIQuote:
Originally Posted by dwks