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;
List.add (num);
}
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