Java中String和byte[]間的 轉換淺析

Java語言中字符串類型和字節數組類型相互之間的轉換常常發生,網上的分析及代碼也比較多,本文將分析總結常規的byte[]和String間的轉換以及十六進制String和byte[]間相互轉換的原理及實現。java

1. String轉byte[]

首先咱們來分析一下常規的String轉byte[]的方法,代碼以下:git

public static byte[] strToByteArray(String str) { if (str == null) { return null; } byte[] byteArray = str.getBytes(); return byteArray; }

很簡單,就是調用String類的getBytes()方法。看JDK源碼能夠發現該方法最終調用了String類以下的方法。github

/** * JDK source code */ public byte[] getBytes(Charset charset) { String canonicalCharsetName = charset.name(); if (canonicalCharsetName.equals("UTF-8")) { return Charsets.toUtf8Bytes(value, offset, count); } else if (canonicalCharsetName.equals("ISO-8859-1")) { return Charsets.toIsoLatin1Bytes(value, offset, count); } else if (canonicalCharsetName.equals("US-ASCII")) { return Charsets.toAsciiBytes(value, offset, count); } else if (canonicalCharsetName.equals("UTF-16BE")) { return Charsets.toBigEndianUtf16Bytes(value, offset, count); } else { CharBuffer chars = CharBuffer.wrap(this.value, this.offset, this.count); ByteBuffer buffer = charset.encode(chars.asReadOnlyBuffer()); byte[] bytes = new byte[buffer.limit()]; buffer.get(bytes); return bytes; } }

上述代碼其實就是根據給定的編碼方式進行編碼。若是調用的是不帶參數的getBytes()方法,則使用默認的編碼方式,以下代碼所示:數組

/** * JDK source code */ private static Charset getDefaultCharset() { String encoding = System.getProperty("file.encoding", "UTF-8"); try { return Charset.forName(encoding); } catch (UnsupportedCharsetException e) { return Charset.forName("UTF-8"); } }

關於默認的編碼方式,Java API是這樣說的:ide

The default charset is determined during virtual-machine startup and typically depends upon the locale and charset of the underlying operating system.測試

一樣,由上述代碼能夠看出,默認編碼方式是由System類的"file.encoding"屬性決定的,通過測試,在簡體中文Windows操做系統下,默認編碼方式爲"GBK",在Android平臺上,默認編碼方式爲"UTF-8"。this

2. byte[]轉String

接下來分析一下常規的byte[]轉爲String的方法,代碼以下:編碼

public static String byteArrayToStr(byte[] byteArray) { if (byteArray == null) { return null; } String str = new String(byteArray); return str; }

很簡單,就是String的構造方法之一。那咱們分析Java中String的源碼,能夠看出全部以byte[]爲參數的構造方法最終都調用了以下代碼所示的構造方法。須要注意的是Java中String類的數據是Unicode類型的,所以上述的getBytes()方法是把Unicode類型轉化爲指定編碼方式的byte數組;而這裏的Charset爲讀取該byte數組時所使用的編碼方式。spa

/** * JDK source code */ public String(byte[] data, int offset, int byteCount, Charset charset) { if ((offset | byteCount) < 0 || byteCount > data.length - offset) { throw failedBoundsCheck(data.length, offset, byteCount); } // We inline UTF-8, ISO-8859-1, and US-ASCII decoders for speed and because // 'count' and 'value' are final. String canonicalCharsetName = charset.name(); if (canonicalCharsetName.equals("UTF-8")) { byte[] d = data; char[] v = new char[byteCount]; int idx = offset; int last = offset + byteCount; int s = 0; outer: while (idx < last) { byte b0 = d[idx++]; if ((b0 & 0x80) == 0) { // 0xxxxxxx // Range: U-00000000 - U-0000007F int val = b0 & 0xff; v[s++] = (char) val; } else if (((b0 & 0xe0) == 0xc0) || ((b0 & 0xf0) == 0xe0) || ((b0 & 0xf8) == 0xf0) || ((b0 & 0xfc) == 0xf8) || ((b0 & 0xfe) == 0xfc)) { int utfCount = 1; if ((b0 & 0xf0) == 0xe0) utfCount = 2; else if ((b0 & 0xf8) == 0xf0) utfCount = 3; else if ((b0 & 0xfc) == 0xf8) utfCount = 4; else if ((b0 & 0xfe) == 0xfc) utfCount = 5; // 110xxxxx (10xxxxxx)+ // Range: U-00000080 - U-000007FF (count == 1) // Range: U-00000800 - U-0000FFFF (count == 2) // Range: U-00010000 - U-001FFFFF (count == 3) // Range: U-00200000 - U-03FFFFFF (count == 4) // Range: U-04000000 - U-7FFFFFFF (count == 5) if (idx + utfCount > last) { v[s++] = REPLACEMENT_CHAR; continue; } // Extract usable bits from b0 int val = b0 & (0x1f >> (utfCount - 1)); for (int i = 0; i < utfCount; ++i) { byte b = d[idx++]; if ((b & 0xc0) != 0x80) { v[s++] = REPLACEMENT_CHAR; idx--; // Put the input char back continue outer; } // Push new bits in from the right side val <<= 6; val |= b & 0x3f; } // Note: Java allows overlong char // specifications To disallow, check that val // is greater than or equal to the minimum // value for each count: // // count min value // ----- ---------- // 1 0x80 // 2 0x800 // 3 0x10000 // 4 0x200000 // 5 0x4000000 // Allow surrogate values (0xD800 - 0xDFFF) to // be specified using 3-byte UTF values only if ((utfCount != 2) && (val >= 0xD800) && (val <= 0xDFFF)) { v[s++] = REPLACEMENT_CHAR; continue; } // Reject chars greater than the Unicode maximum of U+10FFFF. if (val > 0x10FFFF) { v[s++] = REPLACEMENT_CHAR; continue; } // Encode chars from U+10000 up as surrogate pairs if (val < 0x10000) { v[s++] = (char) val; } else { int x = val & 0xffff; int u = (val >> 16) & 0x1f; int w = (u - 1) & 0xffff; int hi = 0xd800 | (w << 6) | (x >> 10); int lo = 0xdc00 | (x & 0x3ff); v[s++] = (char) hi; v[s++] = (char) lo; } } else { // Illegal values 0x8*, 0x9*, 0xa*, 0xb*, 0xfd-0xff v[s++] = REPLACEMENT_CHAR; } } if (s == byteCount) { // We guessed right, so we can use our temporary array as-is. this.offset = 0; this.value = v; this.count = s; } else { // Our temporary array was too big, so reallocate and copy. this.offset = 0; this.value = new char[s]; this.count = s; System.arraycopy(v, 0, value, 0, s); } } else if (canonicalCharsetName.equals("ISO-8859-1")) { this.offset = 0; this.value = new char[byteCount]; this.count = byteCount; Charsets.isoLatin1BytesToChars(data, offset, byteCount, value); } else if (canonicalCharsetName.equals("US-ASCII")) { this.offset = 0; this.value = new char[byteCount]; this.count = byteCount; Charsets.asciiBytesToChars(data, offset, byteCount, value); } else { CharBuffer cb = charset.decode(ByteBuffer.wrap(data, offset, byteCount)); this.offset = 0; this.count = cb.length(); if (count > 0) { // We could use cb.array() directly, but that would mean we'd have to trust // the CharsetDecoder doesn't hang on to the CharBuffer and mutate it later, // which would break String's immutability guarantee. It would also tend to // mean that we'd be wasting memory because CharsetDecoder doesn't trim the // array. So we copy. this.value = new char[count]; System.arraycopy(cb.array(), 0, value, 0, count); } else { this.value = EmptyArray.CHAR; } } }

具體的轉換過程較爲複雜,其實就是將byte數組的一個或多個元素按指定的Charset類型讀取並轉換爲char類型(char自己就是以Unicode編碼方式存儲的),由於String類的核心是其內部維護的char數組。所以有興趣的同窗能夠研究下各類編碼方式的編碼規則,而後才能看懂具體的轉換過程。操作系統

3. byte[]轉十六進制String

所謂十六進制String,就是字符串裏面的字符都是十六進制形式,由於一個byte是八位,能夠用兩個十六進制位來表示,所以,byte數組中的每一個元素能夠轉換爲兩個十六進制形式的char,因此最終的HexString的長度是byte數組長度的兩倍。閒話少說上代碼:

public static String byteArrayToHexStr(byte[] byteArray) { if (byteArray == null){ return null; } char[] hexArray = "0123456789ABCDEF".toCharArray(); char[] hexChars = new char[byteArray.length * 2]; for (int j = 0; j < byteArray.length; j++) { int v = byteArray[j] & 0xFF; hexChars[j * 2] = hexArray[v >>> 4]; hexChars[j * 2 + 1] = hexArray[v & 0x0F]; } return new String(hexChars); }

上述代碼中,之因此要將byte數值和0xFF按位與,是由於咱們爲了方便後面的無符號移位操做(無符號右移運算符>>>只對32位和64位的值有意義),要將byte數據轉換爲int類型,而若是直接轉換就會出現問題。由於java裏面二進制是以補碼形式存在的,若是直接轉換,位擴展會產生問題,如值爲-1的byte存儲的二進制形式爲其補碼11111111,而轉換爲int後爲11111111111111111111111111111111,直接使用該值結果就不對了。而0xFF默認是int類型,即0x000000FF,一個byte值跟0xFF相與會先將那個byte值轉化成int類型運算,這樣,相與的結果中高的24個比特就總會被清0,後面的運算纔會正確。

4. 十六進制String轉byte[]

沒什麼好說的了,就是byte[]轉十六進制String的逆過程,放代碼:

public static byte[] hexStrToByteArray(String str) { if (str == null) { return null; } if (str.length() == 0) { return new byte[0]; } byte[] byteArray = new byte[str.length() / 2]; for (int i = 0; i < byteArray.length; i++){ String subStr = str.substring(2 * i, 2 * i + 2); byteArray[i] = ((byte)Integer.parseInt(subStr, 16)); } return byteArray; }

文中全部代碼能夠在我的github主頁查看和下載。

另,我的技術博客,同步更新,歡迎關注!轉載請註明出處!文中如有什麼錯誤但願你們探討指正!

相關文章
相關標籤/搜索