Conversion of base in java conversion of Byte to hexadecimal

  • 2020-05-17 05:23:43
  • OfStack

In java, there are many ways to convert the base, among which, for the common basic conversion of 2-base 8-base 10-base 106, there are wrapper class implementations, which do not need to be implemented by an algorithm other than 2. The details are as follows:

First of all, the simplest method of binary conversion is as follows:

Convert from base 10 to base 106:
String Integer.toHexString(int i)
Convert from base 10 to base 8
String Integer.toOctalString(int i)
Convert from base 10 to base 2
String Integer.toBinaryString(int i)
Change from base 106 to base 10
Integer.valueOf ("FFFF",16).toString () // cannot handle prefixed situations 0x
Convert from base 8 to base 10
Integer.valueOf ("76",8).toString () // prefix 0 can be processed
Base 2 to base 10
Integer.valueOf("0101",2).toString()

Is there any way to convert 2,8,16 to 10 directly?

java. lang. Integer class

parseInt(String s, int radix)

Parses the string argument into a signed integer using the cardinality specified by the second argument.

examples from jdk:
parseInt("0", 10) returns 0
parseInt("473", 10) returns 473
parseInt("-0", 10) returns 0
parseInt("-FF", 16) returns -255
parseInt("1100110", 2) returns 102
parseInt("2147483647", 10) returns 2147483647
parseInt("-2147483648", 10) returns -2147483648
parseInt("2147483648", 10)throwsa NumberFormatException
parseInt("99",throwsa NumberFormatException
parseInt("Kona", 10)throwsa NumberFormatException
parseInt("Kona", 27)returns 411787

How do I write (2,8,106) without an algorithm
Integer.toBinaryString
Integer.toOctalString
Integer.toHexString

Then the conversion between byte and base 106 in java is introduced

Principle analysis:

byte in Java is composed of 8 bit, while hexadecimal is the 16 medium state, which is represented by 4 bit, because 24=16. So we can convert one byte into two hexadecimal characters, that is, convert the high and low 4 bits into the corresponding hexadecimal characters, and combine the two hexadecimal strings to get the hexadecimal string of byte. Similarly, the reverse conversion converts two hexadecimal characters to one byte.

In Java, there are two main ideas about the interconversion between bytes and base 106:

1. When the binary byte is transferred to 106, do "&" operation with the byte high position and 0xF0, and then move 4 bits to the left to get the 106 base A of the byte high position; Do "&" with the byte low bit and 0x0F to get the low bit hexadecimal B, and combine the two hexadecimal Numbers into one block. AB is the hexadecimal representation of the byte.

2. When the hexadecimal character 106 is transferred to the hexadecimal byte 2, the hexadecimal digit corresponding to the hexadecimal character 106 is moved 4 to the right to obtain the byte high A; "|" operation is performed on the hexadecimal digits B and A corresponding to the hexadecimal characters in the byte low order, and the representation of the hexadecimal bytes in the hexadecimal order of 106 can be obtained

One of the conversion functions is as follows:


/** 
*  
* @param bytes 
* @return  will 2 Base to zero 106 Base character output  
*/ </span>    private static String hexStr = "0123456789ABCDEF"; // global 
	   public static String BinaryToHexString(byte[] bytes){  
   
  String result = "";  
  String hex = "";  
  for(int i=0;i<bytes.length;i++){  
    // High byte 4 position   
    <strong>hex = String.valueOf(hexStr.charAt((bytes[i]&0xF0)>>4)); </strong>
    // Low byte 4 position   
   <strong>hex += String.valueOf(hexStr.charAt(bytes[i]&0x0F)); </strong> 
    result +=hex;  
  }  
  return result;  
	   }  
	   /** 
*  
* @param hexString 
* @return  will 106 Convert the base to a byte array  
*/ 
	   public static byte[] HexStringToBinary(String hexString){  
  //hexString The length of the 2 I'm going to take the whole, as bytes The length of the   
  int len = hexString.length()/2;  
  byte[] bytes = new byte[len];  
  byte high = 0;// High byte 4 position   
  byte low = 0;// Low byte 4 position   
	  
  for(int i=0;i<len;i++){  
    // Moves to the right 4 Bit gets high   
    high = (byte)((hexStr.indexOf(hexString.charAt(2*i)))<<4);  
    low = (byte)hexStr.indexOf(hexString.charAt(2*i+1));  
    bytes[i] = (byte) (high|low);// High position or operation   
  }  
  return bytes;  
	   }  
	 } 

There is a similar method:

< span style="font-size:14px;" > * Convert byte[] to hex string. Here we can convert byte to int and then use Integer.toHexString (int) to convert to hexadecimal strings.


* @param src byte[] data 
 * @return hex string 
 */   
public static String bytesToHexString(byte[] src){ 
  StringBuilder stringBuilder = new StringBuilder(""); 
  if (src == null || src.length <= 0) { 
    return null; 
  } 
  for (int i = 0; i < src.length; i++) { 
    int v = src[i] & 0xFF; 
    String hv = Integer.toHexString(v); 
    if (hv.length() < 2) { 
      stringBuilder.append(0); 
    } 
    stringBuilder.append(hv); 
  } 
  return stringBuilder.toString(); 
} 
/** 
 * Convert hex string to byte[] 
 * @param hexString the hex string 
 * @return byte[] 
 */ 
public static byte[] hexStringToBytes(String hexString) { 
  if (hexString == null || hexString.equals("")) { 
    return null; 
  } 
  hexString = hexString.toUpperCase(); 
  int length = hexString.length() / 2; 
  char[] hexChars = hexString.toCharArray(); 
  byte[] d = new byte[length]; 
  for (int i = 0; i < length; i++) { 
    int pos = i * 2; 
    d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1])); 
  } 
  return d; 
} 
/** 
 * Convert char to byte 
 * @param c char 
 * @return byte 
 */ 
 private byte charToByte(char c) { 
  return (byte) "0123456789ABCDEF".indexOf(c); 
} </span>

The two ways are similar. Notice here

Above is the conversion of byte[] to a string in base 106. Notice that b[i] & 0xFF combines 1 byte and 0xFF, and then USES Integer.toHexString to get a string in base 106, as can be seen

b[i] & 0xFF is still an int, so why sum it with 0xFF? Direct Integer.toHexString(b[i]); , and turn byte strong to int. The answer is no.

The reasons are as follows:

1. The size of byte is 8bits and the size of int is 32bits
2. The base 2 system of java adopts the form of complement

So the negative number will be automatically added to the complement when it is negative &, so there will be errors

And 0xff is by default a plastic, so one byte and one 0xff will convert that byte into a plastic operation, so that the top 24 bits of the result will always be cleared of 0, so that the result will always be what we want.

Here are some other ways to sum up online:

String conversion to base 106 string method 1:


/** 
   *  String conversion to 106 Base string 
   */ 
  public static String str2HexStr(String str) { 
    char[] chars = "0123456789ABCDEF".toCharArray(); 
    StringBuilder sb = new StringBuilder("");
    byte[] bs = str.getBytes(); 
    int bit; 
    for (int i = 0; i < bs.length; i++) { 
      bit = (bs[i] & 0x0f0) >> 4; 
      sb.append(chars[bit]); 
      bit = bs[i] & 0x0f; 
      sb.append(chars[bit]); 
    } 
    return sb.toString(); 
  } 

Convert the base 106 string into an array method 1:


/**
  *  the 16 The base string is converted into a byte array 
  * @param hexString
  * @return byte[]
  */
 public static byte[] hexStringToByte(String hex) {
  int len = (hex.length() / 2);
  byte[] result = new byte[len];
  char[] achar = hex.toCharArray();
  for (int i = 0; i < len; i++) {
  int pos = i * 2;
  result[i] = (byte) (toByte(achar[pos]) << 4 | toByte(achar[pos + 1]));
  }
  return result;
 }
 
 private static int toByte(char c) {
  byte b = (byte) "0123456789ABCDEF".indexOf(c);
  return b;
 }

Array to 106 character string method 1:


/**
 *  Array to 106 Base string 
 * @param byte[]
 * @return HexString
 */
 public static final String bytesToHexString(byte[] bArray) {
 StringBuffer sb = new StringBuffer(bArray.length);
 String sTemp;
 for (int i = 0; i < bArray.length; i++) {
  sTemp = Integer.toHexString(0xFF & bArray[i]);
  if (sTemp.length() < 2)
  sb.append(0);
  sb.append(sTemp.toUpperCase());
 }
 return sb.toString();
 }

byte[] array into 106 base string method 2:


/**
   *  The array into 106 Base string 
   * @param byte[]
   * @return HexString
   */
  public static String toHexString1(byte[] b){
    StringBuffer buffer = new StringBuffer();
    for (int i = 0; i < b.length; ++i){
      buffer.append(toHexString1(b[i]));
    }
    return buffer.toString();
  }
  public static String toHexString1(byte b){
    String s = Integer.toHexString(b & 0xFF);
    if (s.length() == 1){
      return "0" + s;
    }else{
      return s;
    }
  }

String conversion method 1:


/**
 * 106 Converts a base string to a string 
 * @param hexString
 * @return String
 */
  public static String hexStr2Str(String hexStr) { 

    String str = "0123456789ABCDEF"; 
    char[] hexs = hexStr.toCharArray(); 
    byte[] bytes = new byte[hexStr.length() / 2]; 
    int n; 
    for (int i = 0; i < bytes.length; i++) { 
      n = str.indexOf(hexs[2 * i]) * 16; 
      n += str.indexOf(hexs[2 * i + 1]); 
      bytes[i] = (byte) (n & 0xff); 
    } 
    return new String(bytes); 
  }

Hexadecimal string conversion string method 2:


/**
   * 106 Base string converts string 
   * @param HexString
   * @return String
   */
 public static String toStringHex(String s) {
 byte[] baKeyword = new byte[s.length() / 2];
 for (int i = 0; i < baKeyword.length; i++) {
  try {
  baKeyword[i] = (byte) (0xff & Integer.parseInt(s.substring(
   i * 2, i * 2 + 2), 16));
  } catch (Exception e) {
  e.printStackTrace();
  }
 }
 try {
  s = new String(baKeyword, "utf-8");// UTF-16le:Not
 } catch (Exception e1) {
  e1.printStackTrace();
 }
 return s;
 }

Related articles: