How do i convert a int to a binary with bitwise operators only?

And the output must have 32bits place

- 05-23-2010, 05:41 AMdiskhubHow do i convert a int to a binary with bitwise operators only?
How do i convert a int to a binary with bitwise operators only?

And the output must have 32bits place - 05-23-2010, 02:36 PMEranga
What you exactly means by bitwise operator? What's your exact requirement also, because to convert the int into binary string you have several other approaches as well.

- 05-23-2010, 02:39 PMdiskhub
i was told to use only bitwise operation

such as & | >> >>> << ~

to convert int to binary.

there cannot be multiplication n division used in the algorithm.

any clue? - 05-23-2010, 04:09 PMJosAH
- 05-23-2010, 04:13 PMdiskhub
ok, thks for informing

but that doesn't solve my problem

pls advise me how to print it in binary... 10101010111

such that i have to use bitwise operators only. - 05-23-2010, 04:18 PMJosAH
- 05-23-2010, 04:22 PMNorm
Are you asking how to get a String representation of the binary value of an int?

To do that you need to look at each bit position of an int and test if its a 0 or a 1.

Use the AND operator for that.

Remember: 1 AND 1 = 1 1 AND 0 = 0

To look at all 32 bit positions, use the shift operator to move to the next position. - 05-23-2010, 05:24 PMEranga
- 05-23-2010, 05:30 PMEranga
- 05-23-2010, 05:34 PMNorm
It sounded to me like a student's assignment to learn how to use bitwise operators. As an assembler programmer, I think it's good to know what's under the covers.

- 05-23-2010, 05:43 PMEranga
- 05-24-2010, 12:45 AMdiskhub
so no guide?

i thought of one... but might not be a prof way...

that's why i wanted to see what u expert can do... nevermind, i guess u guys are also not used to this tricky question. :D - 05-24-2010, 01:52 AMEranga
No lol. Everyone here in the forum wants to help, including me. But the way you got the question is bit a work. That's what we want you to pointed.

- 05-24-2010, 01:59 AMEranga
Here comes the messy part there, from the API

Code:`private static String toUnsignedString(int i, int shift) {`

char[] buf = new char[32];

int charPos = 32;

int radix = 1 << shift;

int mask = radix - 1;

do {

buf[--charPos] = digits[i & mask];

i >>>= shift;

} while (i != 0);

return new String(buf, charPos, (32 - charPos));

}

- 05-24-2010, 02:00 AMdiskhub
i am thinking of doing this... not sure whether this is good?

for every binary place of a NUM

if (NUM-(NUM>>1<<1)==1)

print "1"

else

print "0"

NUM= NUM>>1

LOOP

but i want to hear from you guys what plan u have? - 05-24-2010, 02:05 AMdiskhub
can u explain the following line of ur code:

int radix = 1 << shift; //what's the shift in this case? what to put for the arg Shift?

digits[i & mask]; // what abt this? - 05-24-2010, 02:11 AMEranga
- 05-24-2010, 02:13 AMEranga
- 05-24-2010, 02:13 AMdiskhub
interesting... i will explore it.

thanks for ur advice.

how's my method, any chance? - 05-24-2010, 02:15 AMEranga