char int byte

本文介绍了一个Java程序,该程序实现了字符串与十六进制之间的相互转换,并提供了字节数组到字符串及字符串到字节数组的转换方法。通过这些方法,可以方便地进行数据格式的转换。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

public static void main(String[] args) {
//String t = encode("15013020645");
byte[] bs = hexToBytes("683133393838383833333333010000B516");
String tt = hexByteToStr(bs);
System.out.println(tt);
}

public static String hexToStr(String hexValue) {
String hex = "0123456789ABCDEF";
char[] hexs = hexValue.toCharArray();
byte[] bytes = new byte[hexValue.length() / 2];
int n;
for (int i = 0; i < bytes.length; i++) {
n = hex.indexOf(hexs[2 * i]) * 16;
n += hex.indexOf(hexs[2 * i + 1]);
bytes[i] = (byte) (n & 0xff);
}
return new String(bytes);
}

public static byte[] hexToBytes(String hexValue) {
String hex = "0123456789ABCDEF";
if (null == hexValue || "".equals(hexValue.trim())) {
return new byte[0];
}
hexValue = hexValue.toUpperCase();
int length = hexValue.length() / 2;
char[] hexChars = hexValue.toCharArray();
byte[] bs = new byte[length];
for (int i = 0; i < length; i++) {
int pos = i * 2;
bs[i] = (byte) (hex.indexOf(hexChars[pos]) << 4 | hex.indexOf(hexChars[pos + 1]));
}
return bs;
}


public static String hexByteToStr(byte[] bs){
return new String(bs);
}








public static String strToHex(String value) {
String hex = "0123456789ABCDEF";
byte[] bytes = value.getBytes();
StringBuilder builder = new StringBuilder(bytes.length * 2);
for (int i = 0; i < bytes.length; i++) {
builder.append(hex.charAt((bytes[i] & 0xf0) >> 4));
builder.append(hex.charAt((bytes[i] & 0x0f) >> 0));
}
return builder.toString();
}



public static char byteToChar(byte[] b) {
int s = 0;
if (b[0] > 0)
s += b[0];
else
s += 256 + b[0];
s *= 256;
if (b[1] > 0)
s += b[1];
else
s += 256 + b[1];
char ch = (char) s;
return ch;
}

public static byte[] charToByte(char ch){
int temp = (int) ch;
byte[] b = new byte[2];
for (int i = b.length - 1; i > -1; i--) {
b[i] = new Integer(temp & 0xff).byteValue();// 将最高位保存在最低位
temp = temp >> 8; // 向右移8位
}
return b;
}

//字符到字节转换
public static int byteToInt(byte[] b) {
int s = 0;
for (int i = 0; i < 3; i++) {
if (b[i] >= 0)
s = s + b[i];
else
s = s + 256 + b[i];
s = s * 256;
}
if (b[3] >= 0)// 最后一个之所以不乘,是因为可能会溢出
s = s + b[3];
else
s = s + 256 + b[3];
return s;
}


public static int byteToInt1(byte[] byteVal) {
int result = 0;
for (int i = 0; i < byteVal.length; i++) {
int tmpVal = (byteVal[i] << (8 * (3 - i)));
switch (i) {
case 0:
tmpVal = tmpVal & 0xFF000000;
break;
case 1:
tmpVal = tmpVal & 0x00FF0000;
break;
case 2:
tmpVal = tmpVal & 0x0000FF00;
break;
case 3:
tmpVal = tmpVal & 0x000000FF;
break;
}
result = result | tmpVal;
}
return result;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值