Hi guys,
Is there a standard lib func that convert a char to binary value?
Hi guys,
Is there a standard lib func that convert a char to binary value?
A char is inherently a binary value, as are all variables.
Code:printf("%c%c%c%c%c%c%c%c", (ch&0x80)?"1":"0", (ch&0x40)?"1":"0", (ch&0x20)?"1":"0", (ch&0x10)?"1":"0", (ch&0x08)?"1":"0", (ch&0x04)?"1":"0", (ch&0x02)?"1":"0", (ch&0x01)?"1":"0" );
Peter O. Programming tips
In the above code, "1" and "0" should be '1' and '0', respectively, to match the format specifiers passed to printf.
Last edited by Dave_Sinkula; 07-31-2003 at 11:55 PM.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
Hi,
Either you use & operator or use standard logic to do this. I have made in standard logic. just call this func.
Code:char* chartobin(int c) { static char binarr[16]; int i; for(i=1;i<=15;i++) { binarr[i]=c%2; c=c/2; } return binarr; }
Saravanan.T.S.
Beginner.
An int is not necessarily 16 bits. And you would need an extra char for the null byte if you want binarr to be a string.Code:char* chartobin(int c) { static char binarr[16]; int i; for(i=1;i<=15;i++) { binarr[i]=c%2; c=c/2; } /* null terminator required to make binarr a string */ return binarr; }
In C, arrays are indexed starting from zero.
The usual idiom is i < 16 (to correspond with the above code).
Last edited by Dave_Sinkula; 08-01-2003 at 09:27 AM.
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
One way to "convert char to binary" might be as follows.Code:#include <stdio.h> #include <limits.h> char *foo(char *dst, unsigned char value) { unsigned char bit; char *start = dst; for ( bit = 1 << (CHAR_BIT - 1); bit; bit >>= 1 ) { *dst++ = value & bit ? '1' : '0'; } *dst = '\0'; return start; } int main(void) { unsigned char u = 117; char b [ CHAR_BIT * sizeof(u) + 1 ]; printf("u = '%c' = 0%o = %d = 0x%X = \"%s\"\n", u, u, u, u, foo(b, u)); return(0); } /* my output u = 'u' = 0165 = 117 = 0x75 = "01110101" */
7. It is easier to write an incorrect program than understand a correct one.
40. There are two ways to write error-free programs; only the third one works.*
>A char is inherently a binary value, as are all variables.
Yes, but a char is not always 8 bits.
>just call this func.
And this works for you? This may work better:
Code:#include <limits.h> char *chartobin ( unsigned char c ) { static char bin[CHAR_BIT + 1] = {0}; int i; for ( i = CHAR_BIT - 1; i >= 0; i-- ) { bin[i] = (c % 2) + '0'; c /= 2; } return bin; }
My best code is written with the delete key.
im trying to get two input from user (enter character one) (enter charater two) then i would like to get it converted to binary then display the hamming distance between two characters how would i do that..