• Post Reply Bookmark Topic Watch Topic
  • New Topic

integer to binary  RSS feed

 
joe jame
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, Im new here and this is my first post.
my homework is to write a program to convert integer to binary.
I have already finish the work and test it out.
The code work fine. However, i feel like my program is too tedious/complicated.
Since i already finish the homework, then this is not cheating.
So the question is: "Is there a easier way to convert integer to binary??"

Here is my code:
 
Raymond Tong
Ranch Hand
Posts: 255
2
IntelliJ IDE Java Spring
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Here you go

Integer.toBinaryString(num)
 
joe jame
Greenhorn
Posts: 2
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I feel so stupid right now.
and thank you.
 
Muhammad Khojaye
Ranch Hand
Posts: 449
IntelliJ IDE Java Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
joe jame wrote:my homework is to write a program to convert integer to binary.

Usually HomeWork Assignments doesn't allow to use library functions. So, double check before using that built-in method
 
Campbell Ritchie
Marshal
Posts: 56570
172
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

Don't use Math.pow in this situation.
What you are trying to do is double something; it is much more efficient to use * 2 than Math.pow. (Or even << 1, which is faster still.)
I suggest you use a StringBuilder instead of the + operator. You can insert a digit at the very first position (0).
Return a 32‑character String, with 00000 at the beginning if necessary.
Find out about the bitwise << and AND operators; I wrote about AND earlier today. There is a link to an earlier post about shift in that post.

And yes, you can simplify that method a lot.
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!