This week's book giveaway is in the General Computing forum.
We're giving away four copies of Arduino in Action and have Martin Evans, Joshua Noble, and Jordan Hochenbaum on-line!
See this thread for details.
The moose likes Java in General and the fly likes Generate bits out of int? Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "Generate bits out of int?" Watch "Generate bits out of int?" New topic
Author

Generate bits out of int?

Amandeep Singh
Ranch Hand

Joined: Jul 17, 2008
Posts: 839

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: 56529
    
  14

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.


[Smart Questions] [JSP FAQ] [Books by Bear] [Bear's FrontMan] [About Bear]
Amandeep Singh
Ranch Hand

Joined: Jul 17, 2008
Posts: 839
Thanks for reply.

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: 19232

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
How To Ask Questions How To Answer Questions
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generate bits out of int?
 
Similar Threads
shift operators
Understanding toHex method?
Storing variables in an array
if - else condition with common code
hamming code(array index out of bounds)