String str = "1134f1aaac"
怎么装换成 byte[] bb bb[0]=11,bb[1]=34,bb[2]=f1,bb[3]=aa,bb[4]=ac
怎么装换成 byte[] bb bb[0]=11,bb[1]=34,bb[2]=f1,bb[3]=aa,bb[4]=ac
解决方案 »
- 关于正则表达式的一个具体困惑
- 程序运行总有错误,不知怎么搞,求救!!
- java运行中出现Exception in thread"main"java.lang.NoSuchMethod的错误
- 关于jdk的版本
- java的输出的现象
- 请问有没有java tutorial 中文版 下载?用google都没找到。(八百里加急~)
- Class database.DBConnectionManager not found!为什么?
- javadoc!
- 小弟刚刚学习JAVA,请大家给我推荐什么值得学习的书,还有谁能和我共同学习~!给我指点迷津呢??
- 有前辈帮忙解释一下吗,详细解释下,谢谢啊
- 我想读取Linux执行命令的返回信息,但读不到完整的,大神帮忙看看
- java的jdk动态代理,这里的动态是怎么体现的?
byte[] bytes = str.getBytes();
for (byte b : bytes) {
System.out.println(b);
}
public static main(String[] args){
String str = "1134f1aaac";
byte[] bytes = str.getBytes();
for (byte b : bytes) {
System.out.println(b);
}
}
}
//测试
public static void main(String[] args) {
String str = "1134f1aaac";
byte[] bb = getBytesFromString(str);
if(bb == null) {
System.out.println("结果是null");
}
//直接显示结果,这样类似“aa”这样的数,都会显示为负。
System.out.println(Arrays.toString(bb));
//转换后显示
for(int i = 0; i < bb.length; i++ ) {
if(i % 8 == 0 ) {
System.out.println();
}
System.out.print("bb[" + i + "] = " + StringToBytes.byteToHexString(bb[i]) + "\t");
}
}
/**
* 转换函数
* @param s
* @return
*/
public static byte[] getBytesFromString(String s) {
//s 如果为空,则返回null.
if(null == s || s.equals("")) {
return null;
}
//大写字母都换成小写。
s = s.toLowerCase();
//用正则表达式判断是否有非数字字符,如含有非数字字符,则返回null.
if(!s.matches("[a-f0-9]+")) {
System.out.println("There is other character!");
return null;
}
//如果长度不是偶数,前面补零, 使长度为偶数。
if(s.length() % 2 != 0) {
s = "0" + s;
} //把字符串变成字节数组,这时数组长度与字符串长度一致,里面的内容是字符的ASCII码。
byte[] temp = s.getBytes();
int length = temp.length;
//定义结果字节数组,其长度是字符串长度的一半。
byte[] result = new byte[length / 2]; //定义几个临时变量。
byte tempByte = 0;
byte tempHigh = 0;
byte tempLower = 0;
//开始转换。
for(int i = 0, j = 0; i < length; i += 2, j++) {
tempByte = temp[i];
if(tempByte >= 48 && tempByte <= 57)
{
tempHigh = (byte)((tempByte - 48) << 4);
}
else if(tempByte >= 97 && tempByte <= 102)//'a'--'e'
{
tempHigh = (byte)((tempByte - 97 + 10) << 4);
}
tempByte = temp[i + 1];
if(tempByte >= 48 && tempByte <= 57)
{
tempLower = (byte)((tempByte - 48));
}
else if(tempByte >= 97 && tempByte <= 102)//'a'--'e'
{
tempLower = (byte)((tempByte - 97 + 10));
}
//每次转换结果放在结果数组里面。
result[j] = (byte)(tempHigh|tempLower);
}
return result;
}
/**
* 把字节整数,转换成16进制字符串。
* @param b
* @return
*/
public static String byteToHexString(byte b) {
int temp = Byte.toUnsignedInt(b);
return Integer.toHexString(temp);
}
}