# Binary, decimal, 16 binary conversion algorithm

Source: Internet
Author: User

This algorithm is not difficult, and there are a number of algorithms for the implementation of today, see a Baidu said that they realized a bit, for reference

Think: decimal number Num,num% 2 The resulting number is stored in the array list, and num = num/2 until num = 0, the resulting array of reverse output is the binary number we want to get

Program:

```public static String to_binary (int orain) {
list<integer> List = new arraylist<> ();

while (orain!=0) {
int num = orain% 2;
Orain = ORAIN/2;
}
String bin = null;
if (list!=null) {
bin = List.get (List.size ()-1) + "";
for (int i= list.size ()-2;i >= 0; i--) {
bin = bin+list.get (i);
}
}
return bin;//Here I am using the string type to save the binary number
}```
Using this method to convert decimal into hexadecimal is the same idea.

Convert binary into decimal

Think: The nth bit is 1 is 1 times 2 of the N-square, note that we write the binary and the order of the calculation is reversed, that is, the 2nd bit in the calculation is 1 times 2 list.size () 1-2 of the second square

```public static double To_decimal (String binary) {

char bin[] = Binary.tochararray ();
list<integer> list = new arraylist<> ();

for (char c:bin) {
List.add (Integer.parseint ("" +c));//convert String to Integer
}

Double num = 0;
int index = List.size ()-1;
for (int i = 0; i < list.size (); i++) {
if (list.get (i) = = 1) {
num = num + math.pow (2, index-i); Index of//2- 1 times
}
}

return num;
}```

Hex turns binary

You can do an intermediate conversion, convert the 16 binary to decimal, and then convert the decimal to binary. The 16 binary is converted to decimal, similar to the binary conversion to decimal, except that the 2 n is replaced by 16. For example 1c = 1*16^1+12*16^0 = 28

Related Keywords:

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.