I need help writing a program that converts full sentences to binary code (ascii -> decimal ->binary), and vice-versa, but I am having trouble doing it. Right now I am working on ascii->binary.
ascii characters have decimal values. a = 97, b = 98, etc. I want to get the decimal value of an ascii character and convert it to a dinary or binary decimal, like 10 (in decimal) in binary is simply:
10 (decimal) == 1010 (binary)
So the ascii decimal value of a and b is:
97, 98
This in binary is (plus the space character which is 32, thanks):
11000011000001100010 == "a b"
11000011100010 == "ab"
I have written this:
int c_to_b(char c)
{
return (printf("%d", (c ^= 64 ^= 32 ^= 16 ^= 8 ^= 4 ^= 2 ^= 1 ^= 0));
}
int s_to_b(char *s)
{
long bin_buf = 0;
for (int i = 0; s[i] != '\0'; i++)
{
bin_buf += s[i] ^= 64 ^= 32 ^= 16 ^= 8 ^= 4 ^= 2 ^= 1 ^= 0;
}
return printf("%d", bin_buf);
}
code examples
main.c
int main(void)
{
// this should print out each binary value for each character in this string
// eg: h = 104, e = 101
// print decimal to binary 104 and 101 which would be equivalent to:
// 11010001100101
// s_to_b returns printf so it should print automatically
s_to_b("hello, world!");
return 0;
}
To elaborate, the for loop in the second snippet loops through each character in the character array until it hits the null terminator. Each time it counts a character, it gets does that operation. Am I using the right operation?
c ^= 64which meansc = c ^ 64? And I don't understand if it is homework, and what is your requirement??