Transformations in Java, Byte and 16 conversion methods _java

Source: Internet
Author: User
Tags stringbuffer

Java in the transformation of the system there are many ways, which for the common basic binary Octal decimal 16 conversion, such as the implementation of the wrapper class, do not need to go through the two algorithm to implement, specifically as follows:

The first method for the simplest binary conversion is:

Decimal turns into 16:
String integer.tohexstring (int i)
Decimal turn into octal system
String integer.tooctalstring (int i)
Decimal turns into binary
String integer.tobinarystring (int i)
Hexadecimal turns to decimal
Integer.valueof ("FFFF"). ToString ()///cannot handle prefixed cases 0x
Octal turn into decimal
Integer.valueof ("8"). ToString ()//prefix 0 can be processed
Binary Turn Decimal
Integer.valueof ("0101", 2). ToString ()

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

Java.lang.Integer class

parseint (String s, int radix)

Resolves a string parameter to a signed integer using the cardinality specified by the second parameter.

Examples from JDK:
parseint ("0", ten) returns 0
parseint ("473", Ten) returns 473
parseint ("-0",) returns 0
parseint ("-ff") returns-255
parseint ("1100110", 2) returns 102
parseint ("2147483647", ten) returns 2147483647
parseint (" -2147483648", returns-2147483648)
parseint ("2147483648", ten) THROWSA numberformatexception
parseint ("Throwsa", numberformatexception
parseint ("Kona", ten) THROWSA numberformatexception
parseint ("Kona",) returns 411787

How to write a binary conversion (two, eight, 16) without an algorithm
Integer.tobinarystring
Integer.tooctalstring
Integer.tohexstring

Then we introduce the conversion of byte and hexadecimal numbers in Java

Principle Analysis:

The byte in Java is made up of 8 bits, and the 16-in-16 state, which is represented by 4 bit, because of the 24=16. So we can convert a byte into two 16 characters, that is, to convert the high 4 bits and the low 4 bits into the corresponding 16 characters, and combine the two 16 binary strings to get the byte 16 string. Similarly, the opposite conversion converts two 16 characters into a byte.

In Java, the main idea of byte-and-hex conversion is two points:

1, binary byte to hexadecimal, the byte high and 0xf0 do "&" operation, and then left 4 bits, get byte high hexadecimal A, byte low and 0x0f do "&" operation, get low hexadecimal B, Assembling two hexadecimal digits to a single AB is the hexadecimal representation of the byte.

2, hexadecimal to binary byte, the hexadecimal character corresponding to the decimal digits to the right to move 4 to get the byte high A; decimal digit B with a byte low hexadecimal character as "|" Operation, you get the hexadecimal binary byte representation

One of the functions of the transformation is as follows:

/** * * @param bytes * @return converts binary to hexadecimal 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++) {//bytes high 4 bit <strong>hex = string.valueof (Hexstr.charat (bytes[i]&0xf 0) (>>4)); </strong>//Byte low 4 bit <strong>hex + = string.valueof (Hexstr.charat (bytes[i]&0x0f));  
  </strong> result +=hex;  
	   return result; /** * * @param hexstring * @return convert 16 to byte array/public static byte[] Hexstringtobinary (String Hexstri  
  NG) {The length of//hexstring is rounded to 2, as the length of the bytes int len = Hexstring.length ()/2;  
  byte[] bytes = new Byte[len]; byte high = 0;//byte height four byte low = 0;//byte lower four bit for (int i=0;i<len;i++) {//Right move four bit to get high = (byte) (  
    Xstr.indexof (Hexstring.charat (2*i))) <<4); Low = (byte) hexstr.indexof (Hexstring.charaT (2*i+1));  
	   Bytes[i] = (byte) (high|low);//high position doing or operation} return bytes; 
 }  
	 }

also has 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 it into a 16-string.  

* @param src byte[] Data * @return Hex String */public static string bytestohexstring (byte[] src) {stringbuild 
  Er 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 (byt 
e) "0123456789ABCDEF". IndexOf (c); } </span>

Two ways like this, notice here

Above is a string that converts byte[] to hexadecimal, note that here b[I & 0xFF a byte and 0xFF and then use integer.tohexstring to get a hexadecimal string that shows

b[i] & 0xFF is still an int, so why and 0xFF? Direct integer.tohexstring (b[i)); Do you want to convert the byte to int? The answer is No.

The reason for this is:

The size of the 1.byte is 8bits and the size of int is 32bits
The 2.java binary uses the complement form

So when negative & negative will automatically give complement 1, so there will be error

And 0xFF is the default, so, a byte and 0xff to participate in the first byte into a plastic operation, so that the result of the high 24 bits will always be clear 0, so the result is always what we want.

There are also some ways to summarize online:

string conversion to hexadecimal string Method 1:

/** 
   * String to hexadecimal 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 (); 
  } 

hexadecimal string conversion becomes array Method 1:

/**
  * Converts a 16-string 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 into hexadecimal string Method 1:

/**
 * Array converted to hexadecimal 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 to hexadecimal string method 2:

/**
   * Array to hexadecimal 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;
    }
  }

Hex string Conversion string Method 1:

/**
 * Hexadecimal string converted to 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)) *; 
      n + = str.indexof (hexs[2 * i + 1]); 
      Bytes[i] = (byte) (n & 0xff); 
    } 
    return new String (bytes); 
  }

Hex string Conversion string Method 2:

/**
   * Hexadecimal string conversion 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.substri NG (
   i * 2, I * 2 + 2));
  catch (Exception e) {
  e.printstacktrace ();
  }
 }
 try {
  s = new String (Bakeyword, "utf-8");//Utf-16le:not
 } catch (Exception E1) {
  e1.printstacktrace (); c19/>} return
 s;
 }

Above this Java in the transformation of the system, byte and 16 conversion method is small series to share all the content, hope to give you a reference, but also hope that we support cloud habitat community.

Contact Us

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.