The JDK has enabled us to implement decimal binary, octal, hex, using integer.tobinarystring (x), integer.tooctalstring (x), integer.tohexstring (x) You can convert x to the corresponding binary, octal, 16-in form. We can also achieve binary, octal and hexadecimal functions by means of displacement operations.
Sample code
@Test public void test02 () {//using JDK to implement int x =-99;
System.out.println (x+ "=" +integer.tobinarystring (x));
System.out.println (x+ "=" +integer.tooctalstring (x));
System.out.println (x+ "=" +integer.tohexstring (x));
@Test public void test01 () {int x =-99;
System.out.println (x+ "=" +tobin (x));
System.out.println (x+ "=" +toba (x));
System.out.println (x+ "=" +tohex (x));
} * * Decimal--> binary */public String toBin (int num) {return trans (num, 1, 1);
/* * Decimal--> octal/public String toBa (int num) {return trans (num, 7, 3);
} * * Decimal--> hexadecimal/public String tohex (int num) {return trans (num, 15, 4);
Public String trans (int num, int base, int offset) {if (num = = 0) {return null;
} char[] chs = {' 0 ', ' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ', ' A ', ' B ', ' C ', ' D ', ' E ', ' F '};
char[] arr = new CHAR[32];
int pos = arr.length;
while (num!= 0) {int temp = num & base;
Arr[--pos] = chs[temp]; Num = num >>> offset;
StringBuilder sb = new StringBuilder ();
for (int x = pos; x < Arr.length + + +) {sb.append (arr[x]);
return sb.tostring (); }
Recently, when doing a project, you need to regroup a byte array by a group of 6bit, to study the implementation of this feature
Implementation code
@org. Junit.test public
void test02 () {
byte B =; byte B = -86;
String str = getallbinarybits (b);
System.out.println (str);
/**
* Converts each byte to a 8-bit binary string form
* @param b
* @return
/private string getallbinarybits (Byte b) {
stringbuffer sb = new StringBuffer ();
Sb.append (b & 128) ==0?0: (b & 128) >>7);
Sb.append ((b &) ==0?0: (b &) >>6);
Sb.append (b &) ==0?0: (b &) >>5);
Sb.append ((b &) ==0?0: (b &) >>4);
Sb.append (b & 8) ==0?0: (b & 8) >>3);
Sb.append (b & 4) ==0?0: (b & 4) >>2);
Sb.append (b & 2) ==0?0: (b & 2) >>1);
Sb.append (b & 1); System.out.println (sb.tostring ());
return sb.tostring ();
}
To convert a byte array, you can set up a for loop