Re: Binary to Hexadecimal Conversion



lei wrote:
you can also suggest for improvements..thanks!


The biggest improvement would be to introduce some functions instead of just having one long main method. Introducing objects might be nice as well, but I suspect this is an exercise pretty early in your class.

The loop converting the binary string to an int should be an int-valued function with a string argument. The computations in this loop could also be done without calls to Math.pow. (Hint: You only need multiplications by 2 and additions.)

It might also be nice to detect overflow here and give an error if the user enters something too large for an int. As it stands, the code just gives the result for the maximum int value if something larger is entered. This could be out of scope for an introductory level assignment though.

A 20 digit hex string is far larger than the maximum int value, so you'll always have leading zeros with this process unless you detect them and don't print them.

But the int[20] array really shouldn't be needed at all. Think about how to build a string from your remainders as you go instead of saving them in an array.

And again, this really should be a function rather than a loop inside main.

Finally, if you really want to impress your teacher, think about going straight from binary string to hex string without ever producing an int, thereby not needing to worry about those integer overflows. This is actually not hard for going from binary to hex or octal. Other bases would be much messier.


.



Relevant Pages