# Bitwise Manipulations in c

Printable View

• 09-22-2009
MrWannabe
Bitwise Manipulations in c
I'm having some problems in an assignment of mine.

The assignment is as follows: with a limited number of legal operations, perform various functions. No conditionals (if's) nor loops are allowed at all.

The legal operations are: <<, >>, +, |, ^, &, ~, !, =

I managed to do some of them, but there are those that I am having trouble with, such as:

1. Negate a number with int negate(int x), such as negate(4) returns -4
I'm not quite sure how to do the necessary two's complement in order to turn the number into a negative.

2. Extract byte n from word x with int getbyte(int x, int n), such as getbyte(0x12345678,1) will return 0x56
I do not understand this problem at all.

3. Find if x <= y with int islessorequal(int x, int y), return 1 if true and 0 if false, such as islessorequal(3,5) should return 1
It sounds simple enough, but limited to binary manipulation makes it rather difficult.

4. Convert from sign-magnitude to two's complement with int sm2tc(int x), where sm2tc(0x80000005) should return -5
I do not understand this byte-related problem either.

5. Find if x is a power of 2 in ispower2(int x) and return 1 if true and 0 if false - as such where ispower2(16) returns 1 and ispower2(15) returns false
This I understand would involve making sure the number contains only one bit with a 1, but I am not sure how to manipulate it without a conditional to discover that sole bit.

_________________________________________________

Any help would be appreciated - thank you!
• 09-22-2009
quzah
We're not here to do your homework for you.
1. Read the homework policy.
2. Read the FAQ on bitwise operators.
3. Try your post again (in the same thread).

Quzah.