Java中字符串與byte數(shù)組之間的相互轉(zhuǎn)換
前言
Java與其他語言編寫的程序進行tcp/ip socket通訊時,通訊內(nèi)容一般都轉(zhuǎn)換成byte數(shù)組型,java在字符與數(shù)組轉(zhuǎn)換也是非常方便的。下面跟我一起來了解一下字符串與byte之間轉(zhuǎn)換的原理
原理
我們都知道,在Java里byte類型是占用1個字節(jié),即8位的,而16進制的字符占用4位,所以每個byte可以用兩個字符來表示,反之亦然。
舉個例子
byte = 123
用二進制表示:0111 1011
每4位用字符表示: 7 b
是的,原理就這么簡單,接下來用代碼實現(xiàn):
byte[] 轉(zhuǎn)16進制字符串
方法一
思路:先把byte[] 轉(zhuǎn)換維char[] ,再把char[] 轉(zhuǎn)換為字符串
public static String bytes2Hex(byte[] src) {
if (src == null || src.length <= 0) {
return null;
}
char[] res = new char[src.length * 2]; // 每個byte對應(yīng)兩個字符
final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
for (int i = 0, j = 0; i < src.length; i++) {
res[j++] = hexDigits[src[i] >> 4 & 0x0f]; // 先存byte的高4位
res[j++] = hexDigits[src[i] & 0x0f]; // 再存byte的低4位
}
return new String(res);
}
方法二
思路:先把byte轉(zhuǎn)換為int類型,再轉(zhuǎn)換為字符串
public static String bytesToHex(byte[] src){
if (src == null || src.length <= 0) {
return null;
}
StringBuilder stringBuilder = new StringBuilder("");
for (int i = 0; i < src.length; i++) {
// 之所以用byte和0xff相與,是因為int是32位,與0xff相與后就舍棄前面的24位,只保留后8位
String str = Integer.toHexString(src[i] & 0xff);
if (str.length() < 2) { // 不足兩位要補0
stringBuilder.append(0);
}
stringBuilder.append(str);
}
return stringBuilder.toString();
}
16進制字符串轉(zhuǎn)byte[]
思路:先把字符串轉(zhuǎn)換為char[] ,再轉(zhuǎn)換為byte[]
public static byte[] hexToBytes(String hexString) {
if (hexString == null || hexString.equals("")) {
return null;
}
int length = hexString.length() / 2;
char[] hexChars = hexString.toCharArray();
byte[] bytes = new byte[length];
String hexDigits = "0123456789abcdef";
for (int i = 0; i < length; i++) {
int pos = i * 2; // 兩個字符對應(yīng)一個byte
int h = hexDigits.indexOf(hexChars[pos]) << 4; // 注1
int l = hexDigits.indexOf(hexChars[pos + 1]); // 注2
if(h == -1 || l == -1) { // 非16進制字符
return null;
}
bytes[i] = (byte) (h | l);
}
return bytes;
}
注:注1得到xxxx0000,注2得到0000xxxx,相或就把兩個字符轉(zhuǎn)換為一個byte了。
再舉個例子
md5加密
public static String getMd5ByFile(File file) {
String ret= null;
FileInputStream fis = null;
try {
fis = new FileInputStream(file);
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] buffer = new byte[1024];
int len;
while((len = fis.read(buffer)) > 0) {
md.update(buffer, 0, len);
}
ret = bytes2Hex(md.digest()); // 把md5加密后的byte[]轉(zhuǎn)換為字符串
} catch (Exception e) {
e.printStackTrace();
} finally {
if(fis != null) {
try {
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return ret;
}
總結(jié)
好了,應(yīng)該懂了吧,其實并不難的。以上就是這篇文章的全部內(nèi)容了,希望這篇文章的內(nèi)容對大家的學(xué)習(xí)或者工作能帶來一定的幫助,如果有疑問大家可以留言交流。
相關(guān)文章
解決redisTemplate向redis中插入String類型數(shù)據(jù)時出現(xiàn)亂碼問題
這篇文章主要介紹了解決redisTemplate向redis中插入String類型數(shù)據(jù)時出現(xiàn)亂碼問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-12-12
DynamicDataSource怎樣解決多數(shù)據(jù)源的事務(wù)問題
這篇文章主要介紹了DynamicDataSource怎樣解決多數(shù)據(jù)源的事務(wù)問題,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-07-07
詳解Spring bean的注解注入之@Autowired的原理及使用
之前講過bean注入是什么,也使用了xml的配置文件進行bean注入,這也是Spring的最原始的注入方式(xml注入).本文主要講解的注解有以下幾個:@Autowired、 @Service、@Repository、@Controller 、@Component、@Bean、@Configuration、@Resource ,需要的朋友可以參考下2021-06-06
為什么ConcurrentHashMap的key value不能為null,map可以?
這篇文章主要介紹了為什么ConcurrentHashMap的key value不能為null,map可以呢?具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧2021-01-01
SpringBoot整合mybatis-plus進階詳細教程
本文主要對mybatis-plus的條件構(gòu)造器、AR模式、插件、逆向工程、自定義全局操作、公共字段自動填充等知識點進行講解,需要的朋友參考下吧2021-09-09

