Reputation: 1493
Is there a way to print binary content of char variable as it is. Means not to convert the variable in to ASCII.
For example,
char c = 1000001;
printf("%c\n", c);
This print
A
But I want to display without convert it to ascii something like below one.
1000001
Is that possible ?
Upvotes: 0
Views: 313
Reputation: 26
can try looping.
scan your character,say 'A'. Get its ASCII(65). Divide 65 by 2 till quotient is zero, store remainder in array/dynmalloc . read the array reverse
65/2 32 1 32/2 16 0 16/2 8 0 8/2 4 0 4/2 2 0 2/2 1 0 1/2 0 1
Upvotes: 1
Reputation: 25885
you can do it by as follows
A char in C is guaranteed to be 1 byte, so loop to 8. Within each iteration, mask off the highest order bit. Once you have it, just print it to standard output.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int main(int argc,char *argv[])
{
char c = 1000001;
int i;
for (i = 0; i < 8; i++) {
printf("%d", !!((c << i) & 0x80));
}
printf("\n");
return 0;
}
or you can also use itoa
library function as follows
char c = 'C'
char output[9];
itoa(c, output, 2);
printf("%s\n", output);
One more solution also
char c = 'C';
int i = 0;
for (i = 7; i >= 0; --i)
{
putchar( (c & (1 << i)) ? '1' : '0' );
}
putchar('\n');
Upvotes: 1