public class StrUtil {
/** 获取byte数组的hex字符串 */
public static String getHexStrOfBytArry(byte[] data) {
StringBuffer buffer = new StringBuffer();
String hex;
for (int i = 0; i < data.length; i++) {
hex = "0" + Integer.toHexString(data[i]);
buffer.append(hex.substring(hex.length() - 2));
}
return buffer.toString();
}
/**
* 将指定字符串src,以每两个字符分割转换为16进制形式 如:"2B44EFD9" –> byte[]{0x2B, 0×44, 0xEF,
* 0xD9}
*
* @param src
* String
* @return byte[]
*/
public static byte[] HexString2Bytes(String src) {
if (null == src || 0 == src.length()) {
return null;
}
byte[] ret = new byte[src.length() / 2];
byte[] tmp = src.getBytes();
for (int i = 0; i < (tmp.length / 2); i++) {
ret[i] = uniteBytes(tmp[i * 2], tmp[i * 2 + 1]);
}
return ret;
}
/**
* 将16进制字符串转为byte数组并反转, len为字节数
*/
public static byte[] HexString2BytesTurn(String src, int len) {
//不足长度补零
while (src.length() / 2 < len) {
src = "0" + src;
}
byte[] result = new byte[len];
List<Byte> blist = new ArrayList<Byte>();
for (int i = 0; i < len; i++) {
blist.add((byte) (Integer.parseInt(src.substring(i * 2, i * 2 + 2), 16) % 256));
}
Collections.reverse(blist);
for (int i = 0; i < len; i++) {
result[i] = blist.get(i);
}
return result;
}
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;
}
public static void main(String[] args) throws NumberFormatException{
// String line = "0x00 0x10 0x02 0x00";
// String line = "0x00";
// System.out.println(line);
// byte[] bb = getByte(line);
// for(int i = 0; i < bb.length; i++){
// System.out.println("xxx=" +bb[i]);
// }
String line = "00000000000000000000000000004C59";
System.out.println(StrUtil.HexString2BytesTurn(line,16));
}
}
Java字符串--字节数组转换工具类
最新推荐文章于 2024-06-06 08:49:23 发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)