In fact, it is estimated that there is no such requirement, just write.
Can we convert it from binary to hexadecimal directly? The most direct way is through the displacement operation, that is, every four bits correspond to a hexadecimal,
If there is a basic binary type in Java, binary Bi = new binary (11010101); in this way, Bi >>> 4 can be easily converted, for more information, see integer. the tohexstring (int I) method in Java.
However, this type does not exist. Java does not seem to have a direct conversion method, so it can only be converted to hexadecimal first and then to hexadecimal.
Write down your own stupid method:
Method 1: It is similar to the hexadecimal conversion in integer source code in some ways.
/*** 10 0010 1111 is separated by four groups. Find the corresponding subscript idx in binarys [] and connect the corresponding hexs [idx. * @ Param binarystr 10 0010 1111 * @ return hexstr 22f */public static string binarytohex (string binarystr) {string binarys [] = new string [] {"0000 ", "0001", "0010", "0011", "0100", "0101", "0110", "0111", "1000", "1001", "1010 ", "1011", "1100", "1101", "1110", "1111"}; string hexs [] = new string [] {"0", "1 ", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B ", "C", "D", "E", "F"}; int n = binarystr. length () % 4; If (n! = 0) {int zeronum = 0; zeronum = 4-N; For (INT I = 0; I <zeronum; I ++) {binarystr = "0" + binarystr ;} N = n + 1;} string hexstr = ""; for (Int J = 0; j <binarystr. length ()/4; j ++) {string temp = binarystr. substring (J * 4, (J + 1) * 4); int Index =-1; for (int K = 0; k <16; k ++) {If (binarys [K]. equals (temp) {Index = K ;}} if (index! =-1) {hexstr = hexstr + hexs [Index] ;}} return hexstr ;}
Method 2: There is only one difference from method 1
/*** 10 0010 1111 is separated by four groups, converted to int-type data index, and then hexs [Index] is added. * @ Param binarystr 10 0010 1111 * @ return hexstr 22f */public static string binarytohex2 (string binarystr) {string hexs [] = new string [] {"0 ", "1", "2", "3", "4", "5", "6", "7", "8", "9", "", "B", "C", "D", "E", "F"}; int n = binarystr. length () % 4; If (n! = 0) {int zeronum = 0; zeronum = 4-N; For (INT I = 0; I <zeronum; I ++) {binarystr = "0" + binarystr ;} N = n + 1;} string hexstr = ""; for (Int J = 0; j <binarystr. length ()/4; j ++) {string temp = binarystr. substring (J * 4, (J + 1) * 4); int Index = 0; // subscript Index = 15, the corresponding output hexs [15] = f int I = 3; for (char C: temp. tochararray () {string STR = new string (New char [] {c}); Index = index + (integer. parseint (STR) <I); I --;} hexstr = hexstr + hexs [Index];} return hexstr ;}
The preceding method is less efficient and involves string operations.
About binary conversion to hexadecimal