Check out Manning's Countdown to 2014. Use discount code crdotd14 all month for 50% off every deal.
Big Moose Saloon
 Search | Java FAQ | Recent Topics Register / Login

# Generate bits out of int?

Amandeep Singh
Ranch Hand

Joined: Jul 17, 2008
Posts: 844

represented in bits as-

But how do we generate bits out of int in java?

SCJP 1.4, SCWCD 5, SCBCD 5, OCPJWSD 5,SCEA-1, Started Assignment Part 2
My blog- http://rkydesigns.blogspot.com
Bear Bibeault
Author and ninkuma
Marshal

Joined: Jan 10, 2002
Posts: 58842

59

What's your algorithm? As the bits are the binary representation of the value, how would you generate the base 2 equivalent? In the US, this is 6th-grade math.

Amandeep Singh
Ranch Hand

Joined: Jul 17, 2008
Posts: 844

Following is my algorithm-

Yes, it is basics and I believe I learnt in 5th grade . I know on a piece of paper, I can calculate.

But in java, I'm looking for a method which changes it into machine readable bits. The algorithm which is used behind the scenes to manipulate the code or understand the int 11. I meant to say, I don't want to define my algorithm to calculate the bits. There should be inbuilt in java too to calculate the bits. What algorithm/method would be to calculate the bits?

Pardon me, if you think it is too stupid question.
Claudiu Chelemen
Ranch Hand

Joined: Mar 25, 2011
Posts: 67

Doesn't the toBinaryString static method accomplish this ? eg:

From there on, you can break it into byte[] or char[] easily.

Cheers!
Hunter McMillen
Ranch Hand

Joined: Mar 13, 2009
Posts: 490

If you repeatedly divide the number by 2, the remainders will be the binary form of the number.

ex: # = 23

23 / 2 = 11 R 1 <- 1
11/2 = 5 R 1 <- 2
5 /2 = 2 R 1 <- 4
2/2 = 1 R 0
1/2 = 0 R 1 <- 16

10111 = 23

Hunter

Edit: reorder the numbers, I ordered them in reverse even though I wrote the correct values next to them.

"If the facts don't fit the theory, get new facts" --Albert Einstein
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19416

13

Surely you mean 10111? Your algorithm works, you just need to add the new numbers to the start, not the end.

SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6