Convert Char to Binary in C

I am trying to convert a character to its binary representation (therefore character -> ascii hex -> binary).

I know that I need to shift AND . However, my code does not work for some reason.

Here is what I have. *temp points to the index on line C.

 char c; int j; for (j = i-1; j >= ptrPos; j--) { char x = *temp; c = (x >> i) & 1; printf("%d\n", c); temp--; } 
+4
c string char binary ascii
source share
2 answers

We show two functions that print the SINGLE character to a binary file.

 void printbinchar(char character) { char output[9]; itoa(character, output, 2); printf("%s\n", output); } 

printbinchar (10) writes to the console

  1010 

itoa is a library function that converts a single integer value to a string with the specified base. For example ... itoa (1341, output, 10) will write "1341" in the output line. And of course, itoa (9, output, 2) will write "1001" in the output line.

The following function will print the full binary representation of the character on the standard output, that is, it will print all 8 bits, also if the highest bits are zero.

 void printbincharpad(char c) { for (int i = 7; i >= 0; --i) { putchar( (c & (1 << i)) ? '1' : '0' ); } putchar('\n'); } 

printbincharpad (10) writes to the console

  00001010 

Now I present a function that outputs an entire string (without the last null character).

 void printstringasbinary(char* s) { // A small 9 characters buffer we use to perform the conversion char output[9]; // Until the first character pointed by s is not a null character // that indicates end of string... while (*s) { // Convert the first character of the string to binary using itoa. // Characters in c are just 8 bit integers, at least, in noawdays computers. itoa(*s, output, 2); // print out our string and let write a new line. puts(output); // we advance our string by one character, // If our original string was "ABC" now we are pointing at "BC". ++s; } } 

Note, however, that itoa does not add zero zeros, so printstringasbinary ("AB1") will print something like:

 1000001 1000010 110001 
+21
source share

Your code is very vague and incomprehensible, but I can provide you with an alternative.

First of all, if you want temp go through the whole line, you can do something like this:

 char *temp; for (temp = your_string; *temp; ++temp) /* do something with *temp */ 

The term *temp as a for condition simply checks if you have reached the end of the line or not. If you have, *temp will be '\0' ( NUL ) and ends with for .

Now, inside the for, you want to find the bits that make up *temp . Say we print a bit:

 for (as above) { int bit_index; for (bit_index = 7; bit_index >= 0; --bit_index) { int bit = *temp >> bit_index & 1; printf("%d", bit); } printf("\n"); } 

To make it more universal, that is, convert any type to bit, you can change bit_index = 7 to bit_index = sizeof(*temp)*8-1

+2
source share

All Articles