• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • Liutauras Vilda
  • Bear Bibeault
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Devaka Cooray
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Piet Souris
  • salvin francis
  • Stephan van Hulst
Bartenders:
  • Frits Walraven
  • Carey Brown
  • Jj Roberts

integer to binary

 
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:
 
Ranch Hand
Posts: 258
2
IntelliJ IDE Spring Java
  • 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.
 
Ranch Hand
Posts: 449
Scala IntelliJ IDE Java
  • 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
 
Marshal
Posts: 71097
292
  • 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.
reply
    Bookmark Topic Watch Topic
  • New Topic