# fastest way to NOT a binary sequence in decimal form

This is a discussion on fastest way to NOT a binary sequence in decimal form within the C Programming forums, part of the General Programming Boards category; I have a decimal, say 8, which is 1000 in binary. What I want to do is to NOT the ...

1. ## fastest way to NOT a binary sequence in decimal form

I have a decimal, say 8, which is 1000 in binary. What I want to do is to NOT the sequence so it becomes 0111 and then get 7. Now the manual way is to just convert 8 to binary and then XOR with 1111 to get 0111. Then finally converting 0111 to 7. I was wondering if there was a way to skip the conversion and directly go from 8 to 7?

2. Inverting ~8 will be fastest due to underlying hardware support for such operations.

3. Code:
```\$ cat foo.c
#include <stdio.h>
int main ( ) {
int a = 8;
printf("%d\n",(~a)&0x0F );
return 0;
}
\$ gcc foo.c
\$ ./a.out
7```

4. I think part of your confusion is this concept of "conversion". The computer only deals in binary. When it shows you a decimal number, it's showing you the decimal representation of the underlying binary data. When you type in a decimal number, the functions like scanf and strtol convert that text to a number. That number is stored in binary. All those decimal numbers you type when programming get converted to binary when the compiler generates code. Also, as Salem pointed out, C has a bitwise NOT operator, the ~. It's equivalent to XORing with all 1's, but it's clearer and as fast or faster.

5. how would i get it working with 8 bit numbers? the not operator works great, but seems like 0x0f only deals with the 4bit to the right most.

6. thanks

7. Originally Posted by tianshiz
how would i get it working with 8 bit numbers? the not operator works great, but seems like 0x0f only deals with the 4bit to the right most.
Well, your examples only dealt with the rightmost nibble (4-bit chunk), so naturally Salem's suggestion did likewise. The ~ operator will work with signed and unsigned versions of char as well as short, int, long, long long. Just declare an 8-bit variable (char or unsigned char), and use the ~ without the & 0x0f bit.

8. Originally Posted by tianshiz
how would i get it working with 8 bit numbers? the not operator works great, but seems like 0x0f only deals with the 4bit to the right most.
Code:
```#include <stdio.h>

int main (void)
{ unsigned int x  =  0;

printf("%d  %d", x, ~x);

return 0; }```
You can always do little tests like this... it's a great way to learn what does what.