joe jame

Greenhorn

Posts: 2

posted 4 years ago

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:

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:

Campbell Ritchie

Marshal

Posts: 56570

172

posted 4 years ago

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.

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. |