六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 49|回复: 0

Java整数-字节,字节-字符,字节数组-十六进制字符串转换

[复制链接]

升级  55.33%

35

主题

35

主题

35

主题

秀才

Rank: 2

积分
133
 楼主| 发表于 2013-2-1 12:16:49 | 显示全部楼层 |阅读模式
[转] (源地址忘了-,-!)
 
// 整数到字节数组转换 
public static byte[] int2bytes(int n) {
byte[] ab = new byte[4];
ab[
0= (byte) (0xff & n);
ab[
1= (byte) ((0xff00 & n) >> 8);
ab[
2= (byte) ((0xff0000 & n) >> 16);
ab[
3= (byte) ((0xff000000 & n) >> 24);
return ab;
}
 

// 字节数组到整数的转换 
public static int bytes2int(byte b[]) {
int s = 0;
= ((((b[0& 0xff<< 8 | (b[1& 0xff)) << 8| (b[2& 0xff)) << 8 
| (b[3& 0xff);
return s;
}
 

// 字节转换到字符 
public static char byte2char(byte b) {
return (char) b;
}
 

private final static byte[] hex = "0123456789ABCDEF".getBytes();

private static int parse(char c) {
if (c >= 'a')
return (c - 'a' + 10& 0x0f;
if (c >= 'A')
return (c - 'A' + 10& 0x0f;
return (c - '0'& 0x0f;
}
 

// 从字节数组到十六进制字符串转换 
public static String Bytes2HexString(byte[] b) {
byte[] buff = new byte[2 * b.length];
for (int i = 0; i < b.length; i++{
buff[
2 * i] = hex[(b >> 4& 0x0f];
buff[
2 * i + 1= hex[b & 0x0f];
}
 
return new String(buff);
}
 

// 从十六进制字符串到字节数组转换 
public static byte[] HexString2Bytes(String hexstr) {
byte[] b = new byte[hexstr.length() / 2];
int j = 0;
for (int i = 0; i < b.length; i++{
char c0 = hexstr.charAt(j++);
char c1 = hexstr.charAt(j++);
b 
= (byte) ((parse(c0) << 4| parse(c1));
}
 
return b;
}
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表