JAVA Learning-in-the-process transformation

Source: Internet
Author: User
Tags decimal to binary

Write a function trans ();

1 Decimal to binary binary

2 ability to decimal to octal

3 ability to decimal to hexadecimal

4 Package functions

Code implementation:

Class Arrarytest {public static void main (string[] args) {int num=60; String str_bin=tobinary (num); String str_oct=tooctal (num); String Str_hex=tohex (num); System.out.println ("Self-defined conversions"); System.out.println ("Bin:" +str_bin); System.out.println ("Oct:" +str_oct); System.out.println ("Hex:" +str_hex); SYSTEM.OUT.PRINTLN ("System comes with the conversion"); System.out.println (integer.tobinarystring (60)); System.out.println (integer.tooctalstring (60)); System.out.println (integer.tohexstring (60));}    Decimal to hexadecimal public static String tohex (int num) {return "0x" +trans (num,15,4);}    Decimal to binary public static String tobinary (int num) {return trans (num,1,1);} Decimal to octal public static String tooctal (int num) {return "0" +trans (num,7,3);} Call the trans function to convert public static String trans (int num,int base,int offset) {///base bitwise with the number of offset right shift number if (num==0) return "0        "; Hit table completion conversion char []chs={' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '};char []arr=new char[32]; int index=arr.length;///specific operation while (num!=0) {int Temp=num&base;arr[--index]=chs[temp];num=num>>>offset;} Return toString (Arr,index);} Numeric to String function public static string toString (char []arr,int POS) {String temp= "", for (int i=pos;i<arr.length;++i) {temp+= Arr[i];} return temp;}}


Operation Result:


My first Java program feels okay.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

JAVA Learning-in-the-process transformation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.