Rabu, 12 Maret 2014

How to convert decimal to binary, octal and hex String in Java Program




This article is about a simple java program which converts decimal number to binary, octal and hexadecimal format. When it was first came into my mind I though I would probably need to write whole code to convert decimal to various other radix or base numbers but when I looked Integer class and saw these two way of converting decimal to binary etc I was simple amazed. It’s indeed extremely easy to do this in java and you can also write this program or use at it is.



Converting decimal to binary in Java Example




convert decimal number to binary in java exampleJava  has many ways to change number system of particular number, you can convert any decimal number into either binary system, hexadecimal system or octal system by following same procedure. here is code example of converting any decimal number into binary number in Java.



      


//first way      


        //decimal to binary


        String binaryString = Integer.toBinaryString(number);


        System.out.println("decimal to binary: " + binaryString);


      


        //decimal to octal


        String octalString = Integer.toOctalString(number);


        System.out.println("decimal to octal: " + octalString);


      


        //decimal to hexadecimal


        String hexString = Integer.toHexString(number);


        System.out.println("decimal to hexadecimal: " + hexString);





      


//second way


        binaryString = Integer.toString(number,2);


        System.out.println("decimal to binary using Integer.toString: " + binaryString);


      


        //decimal to octal


        octalString = Integer.toString(number,8);


        System.out.println("decimal to octal using Integer.toString: " + octalString);


      


        //decimal to hexadecimal


        hexString = Integer.toString(number,16);


        System.out.println("decimal to hexadecimal using Integer.toString: " + hexString);









Nice and little tip to convert decimal to binary or decimal to Octal, hex. This comes very handy many times when we want to do a quick conversion.





Related Java Tutorials
































Source:http://javarevisited.blogspot.com/2011/10/convert-decimal-binary-octal-java.html

Tidak ada komentar:

Posting Komentar