Ok..I get how to do binary division and have written this simple program (everything except the output with putchar()). My goal, however, is to invert my input and print it out. I ran into a few problems trying to accomplish this:

- How do I get the one's complement operator ~ to work? I've tried inserting it here and there but all i get is smiley faces or some funky symbols.

- In putchar, what does '0' + r do?

``````/*
1. Get bits of unsigned char x and store into y.
2. Invert.
*/

#include <stdio.h>

int to_binary(int);

void main(void)
{
unsigned char x, y;

puts("Enter a value for x:");
scanf("%d", &x);
y = to_binary(x);

}

int to_binary(int n)
{
int r;

r = n % 2;
if (n >= 2)
to_binary(n / 2);
putchar('0' + r);
return r;
}``````

- How do I get the one's complement operator ~ to work? I've tried inserting it here and there but all i get is smiley faces or some funky symbols.

The one's complement operator subtracts your number from the maximum possible unsigned integer that can be stored. For example, if you're using an unsigned char, the maximum possible unsigned char is 255. So ~ch is equivalent to 255 - ch. This is equivalent to flipping the value of all the bits in ch. If you're using an int, the maximum possible unsigned integer is equal to 4294967295, so ~x is equivalent to 4294967295 - x.

Try `unsigned int x = 45; printf("%u", ~x);` . I have a feeling you tried printing out bitwise complemented value as a character, instead of printing its decimal representation.

- In putchar, what does '0' + r do?

'0' is a way of writing the integer value that represents the character 0. This value (in the ASCII character set) is 48. So '0' + r is equivalent to writing 48 + r. Remember that a character is stored internally as an integer.

So if r is 1, then 48 + r gives the value 49, which is the ascii value for the character '1'.

Ahh ok that clears up a lot of things. thx

Be a part of the DaniWeb community

We're a friendly, industry-focused community of 1.18 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.