2 to -2 in c
how to invert 2 to -2 with bit operation in c programming language.
main(){ int x=2; int y; y= .... /* bit operations */ ........ printf("%d",y); // -2 } |
Do not expect LQ members to do your homework - you will learn much more by doing it yourself.
|
I can't say that I know how to do that but you can have a look and see what NOT gives you.
|
|
To understand the problem, I suggest printing the numbers of interest in binary format. From that you will be able to see the patterns which should reveal the boolean logic required to achieve the transformation. As Hko points out, you should also understand the nature of two's complement integer format and related arithmetic. A book or online tutorial in assembler language may be a useful resource for learning this subject.
--- rod. |
There's no way to do it purely with bit operations unless you make assumptions about the system you're working on. int isn't always signed, either, so you need signed int to be sure. Unless you just assume what bit is the sign bit, you need to use a different signed/unsigned pair to derive which bit it actually is. If you can infer what I mean it will be a very easy task, though a portable solution is just a long way of saying * -1 or | -0.
ta0kira |
Quote:
Code:
y = x*-1; Optional Also if you want to check the number whether it's negative or positive before convert it you can make an if statement. Code:
if (x>0) |
...but those aren't bit operators.
|
HKO's wiki link tells you how to do exactly this via bit operations. It however does not show you the code on how to do it so you will need to write that yourself.
Hell it even gives you the logic just gotta fill in the code bits :P |
Quote:
|
#include <stdio.h>
int main() { int x; scanf("%d",&x); x=~(x-1); printf("%d\n",x); return 0; } |
Quote:
Code:
int y = (int)(~((unsigned int)x))+1; |
But +1 isn't a bit operation ;)
|
Quote:
|
Quote:
|
All times are GMT -5. The time now is 07:25 AM. |