JAVA 十六進制與字符串的轉換
筆者前幾日在開服過程中需要將字符串轉化成為16進制的字符串,在網(wǎng)上找到了一些方法嘗試之后,均發(fā)現(xiàn)存在一個問題-->字符串轉為16進制后再轉回來,英文正常,中文出現(xiàn)亂碼
經(jīng)過考慮決定通過以下方式進行解決:
1)在將字符串轉為16進制之前先進行一次轉化,先將其轉化成為Unicode編碼(相當于把中文用英文字符代替),在轉化成為16進制
2)相反的,在十六進制轉換為字符串后的得到的是Unicode編碼,此時再將Unicode編碼解碼即可獲取原始字符串
代碼如下:
/**
* 字符串轉換unicode
*/
public static String string2Unicode(String string) {
StringBuffer unicode = new StringBuffer();
for (int i = 0; i < string.length(); i++) {
// 取出每一個字符
char c = string.charAt(i);
// 轉換為unicode
unicode.append("\\u" + Integer.toHexString(c));
}
return unicode.toString();
}
*字符串轉為16進制
/**
* 字符串轉化成為16進制字符串
* @param s
* @return
*/
public static String strTo16(String s) {
String str = "";
for (int i = 0; i < s.length(); i++) {
int ch = (int) s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
*16進制轉為字符串
/**
* 16進制轉換成為string類型字符串
* @param s
* @return
*/
public static String hexStringToString(String s) {
if (s == null || s.equals("")) {
return null;
}
s = s.replace(" ", "");
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");
new String();
} catch (Exception e1) {
e1.printStackTrace();
}
return s;
}
*Unicode轉為字符串
/**
* unicode 轉字符串
*/
public static String unicode2String(String unicode) {
StringBuffer string = new StringBuffer();
String[] hex = unicode.split("\\\\u");
for (int i = 1; i < hex.length; i++) {
// 轉換出每一個代碼點
int data = Integer.parseInt(hex[i], 16);
// 追加成string
string.append((char) data);
}
return string.toString();
}
此方法雖然解決了轉化過程中中文亂碼的問題,但是過于復雜,筆者后來又發(fā)現(xiàn)一種新的轉化方式,可直接轉化,中文不亂碼,
代碼如下:
*字符串轉16進制
/**
* 字符串轉換成為16進制(無需Unicode編碼)
* @param str
* @return
*/
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]);
// sb.append(' ');
}
return sb.toString().trim();
}
*16進制轉為字符串
/**
* 16進制直接轉換成為字符串(無需Unicode解碼)
* @param hexStr
* @return
*/
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);
}
下面是補充
java字符串和十六進制字符串互轉
public class HexStringUtils {
private static final char[] DIGITS_HEX = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D',
'E', 'F' };
protected static char[] encodeHex(byte[] data) {
int l = data.length;
char[] out = new char[l << 1];
for (int i = 0, j = 0; i < l; i++) {
out[j++] = DIGITS_HEX[(0xF0 & data[i]) >>> 4];
out[j++] = DIGITS_HEX[0x0F & data[i]];
}
return out;
}
protected static byte[] decodeHex(char[] data) {
int len = data.length;
if ((len & 0x01) != 0) {
throw new RuntimeException("字符個數(shù)應該為偶數(shù)");
}
byte[] out = new byte[len >> 1];
for (int i = 0, j = 0; j < len; i++) {
int f = toDigit(data[j], j) << 4;
j++;
f |= toDigit(data[j], j);
j++;
out[i] = (byte) (f & 0xFF);
}
return out;
}
protected static int toDigit(char ch, int index) {
int digit = Character.digit(ch, 16);
if (digit == -1) {
throw new RuntimeException("Illegal hexadecimal character " + ch + " at index " + index);
}
return digit;
}
public static String toHex(String str) {
return new String(encodeHex(str.getBytes()));
}
public static String fromHex(String hex) {
return new String(decodeHex(hex.toCharArray()));
}
public static void main(String[] args) {
String s = "abc你好";
String hex = toHex(s);
String decode = fromHex(hex);
System.out.println("原字符串:" + s);
System.out.println("十六進制字符串:" + hex);
System.out.println("還原:" + decode);
}
}
toHexString
public static String toHexString(int i)以十六進制的無符號整數(shù)形式返回一個整數(shù)參數(shù)的字符串表示形式。
如果參數(shù)為負,那么無符號整數(shù)值為參數(shù)加上 232;否則等于該參數(shù)。將該值轉換為十六進制(基數(shù) 16)的無前導 0 的 ASCII 數(shù)字字符串。如果無符號數(shù)的大小值為零,則用一個零字符 '0' ('\u0030') 表示它;否則,無符號數(shù)大小的表示形式中的第一個字符將不是零字符。用以下字符作為十六進制數(shù)字:
0123456789abcdef
這些字符的范圍是從 '\u0030' 到 '\u0039' 和從 '\u0061' 到 '\u0066'。如果希望得到大寫字母,可以在結果上調(diào)用 String.toUpperCase() 方法:
Integer.toHexString(n).toUpperCase()
參數(shù):
i - 要轉換成字符串的整數(shù)。
返回:
用十六進制(基數(shù) 16)參數(shù)表示的無符號整數(shù)值的字符串表示形式。
// 轉化字符串為十六進制編碼
public static String toHexString(String s)
{
String str="";
for (int i=0;i<s.length();i++)
{
int ch = (int)s.charAt(i);
String s4 = Integer.toHexString(ch);
str = str + s4;
}
return str;
}
// 轉化十六進制編碼為字符串
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;
}
// 轉化十六進制編碼為字符串
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;
}
public static void main(String[] args) {
System.out.println(encode("中文"));
System.out.println(decode(encode("中文")));
}
/*
* 16進制數(shù)字字符集
*/
private static String hexString="0123456789ABCDEF";
/*
* 將字符串編碼成16進制數(shù)字,適用于所有字符(包括中文)
*/
public static String encode(String str)
{
//根據(jù)默認編碼獲取字節(jié)數(shù)組
byte[] bytes=str.getBytes();
StringBuilder sb=new StringBuilder(bytes.length*2);
//將字節(jié)數(shù)組中每個字節(jié)拆解成2位16進制整數(shù)
for(int i=0;i<bytes.length;i++)
{
sb.append(hexString.charAt((bytes[i]&0xf0)>>4));
sb.append(hexString.charAt((bytes[i]&0x0f)>>0));
}
return sb.toString();
}
/*
* 將16進制數(shù)字解碼成字符串,適用于所有字符(包括中文)
*/
public static String decode(String bytes)
{
ByteArrayOutputStream baos=new ByteArrayOutputStream(bytes.length()/2);
//將每2位16進制整數(shù)組裝成一個字節(jié)
for(int i=0;i<bytes.length();i+=2)
baos.write((hexString.indexOf(bytes.charAt(i))<<4 |hexString.indexOf(bytes.charAt(i+1))));
return new String(baos.toByteArray());
}
第二種方法:
將指定byte數(shù)組以16進制的形式打印到控制臺
package com.nantian.iclient.atm.sdb;
public class Util {
public Util() {
}
/**
* 將指定byte數(shù)組以16進制的形式打印到控制臺
* @param hint String
* @param b byte[]
* @return void
*/
public static void printHexString(String hint, byte[] b) {
System.out.print(hint);
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
System.out.print(hex.toUpperCase() + " ");
}
System.out.println("");
}
/**
*
* @param b byte[]
* @return String
*/
public static String Bytes2HexString(byte[] b) {
String ret = "";
for (int i = 0; i < b.length; i++) {
String hex = Integer.toHexString(b[i] & 0xFF);
if (hex.length() == 1) {
hex = '0' + hex;
}
ret += hex.toUpperCase();
}
return ret;
}
/**
* 將兩個ASCII字符合成一個字節(jié);
* 如:"EF"--> 0xEF
* @param src0 byte
* @param src1 byte
* @return byte
*/
public static byte uniteBytes(byte src0, byte src1) {
byte _b0 = Byte.decode("0x" + new String(new byte[]{src0})).byteValue();
_b0 = (byte)(_b0 << 4);
byte _b1 = Byte.decode("0x" + new String(new byte[]{src1})).byteValue();
byte ret = (byte)(_b0 ^ _b1);
return ret;
}
/**
* 將指定字符串src,以每兩個字符分割轉換為16進制形式
* 如:"2B44EFD9" --> byte[]{0x2B, 0x44, 0xEF, 0xD9}
* @param src String
* @return byte[]
*/
public static byte[] HexString2Bytes(String src){
byte[] ret = new byte[8];
byte[] tmp = src.getBytes();
for(int i=0; i<8; i++){
ret[i] = uniteBytes(tmp[i*2], tmp[i*2+1]);
}
return ret;
}
}
以上就是JAVA 十六進制與字符串的轉換的詳細內(nèi)容,更多關于JAVA 十六進制的資料請關注腳本之家其它相關文章!
- Java 正則表達式詳解
- JAVA8 十大新特性詳解
- Java環(huán)境變量的設置方法(圖文教程)
- java寫入文件的幾種方法分享
- javascript的console.log()用法小結
- JavaScript window.setTimeout() 的詳細用法
- JavaScript 下拉菜單實現(xiàn)代碼
- javascript getElementById 使用方法及用法
- IIS Express 取代 ASP.NET Development Server的配置方法
- 將IIS Express改成可以通過ip地址訪問的設置方法
- 使用本機IIS?Express開發(fā)Asp.Net?Core應用圖文教程
- 設置IIS Express并發(fā)數(shù)
- VS2015 IIS Express無法啟動的解決方法
- IISExpress?配置允許外部訪問詳細介紹
相關文章
Java 下數(shù)據(jù)業(yè)務邏輯開發(fā)技術 JOOQ 和 SPL
這篇文章主要為大家介紹了Java 下數(shù)據(jù)業(yè)務邏輯開發(fā)技術 JOOQ 和 SPL詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-09-09
IntelliJ?IDEA?2022.2最新版本激活教程(親測可用版)永久激活工具分享
Jetbrains官方發(fā)布了?IntelliJ?IDEA2022.2?正式版,每次大的版本更新,都會有較大的調(diào)整和優(yōu)化,除本次更新全面擁抱?Java?17?外,還有對IDE?UI界面,安全性,便捷性等都做了調(diào)整和優(yōu)化完善,用戶體驗提升不少,相信后面會有不少小伙伴跟著更新2022-08-08
Java數(shù)據(jù)庫連接_jdbc-odbc橋連接方式(詳解)
下面小編就為大家?guī)硪黄狫ava數(shù)據(jù)庫連接_jdbc-odbc橋連接方式(詳解)。小編覺得挺不錯的,現(xiàn)在就分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2017-08-08
Spring實現(xiàn)源碼下載編譯及導入IDEA過程圖解
這篇文章主要介紹了Spring實現(xiàn)源碼下載編譯及導入IDEA,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-07-07
java中gradle項目報錯org.gradle?.api.plugins.MavenPlugin解決辦法
在使用Gradle時開發(fā)者可能會遇到org.gradle?.api.plugins.MavenPlugin報錯提醒,這篇文章主要給大家介紹了關于java中gradle項目報錯org.gradle?.api.plugins.MavenPlugin的解決辦法,需要的朋友可以參考下2023-12-12

