public class CommandUtil {
/**
* 把int类型的数据转换成4个字节的byte数组.数组从0-n依次表高位到低位
*
* @param value
* @return
*/
public static byte[] convertInt2Bytes(int value) {
byte[] bs = new byte[4];
bs[3] = (byte) (value & 0xFF);
bs[2] = (byte) ((value >> 8) & 0xFF);
bs[1] = (byte) ((value >> 16) & 0xFF);
bs[0] = (byte) ((value >> 24) & 0xFF);
return bs;
}
/**
* 把Short类型的数据转换成4个字节的byte数组.数组从0-n依次表高位到低位
*
* @param value
* @return
*/
public static byte[] convertShort2Bytes(Short value) {
byte[] bs = new byte[2];
bs[1] = (byte) (value & 0xFF);
bs[0] = (byte) ((value >> 8) & 0xFF);
return bs;
}
/**
* 把byte数组转成int类型,byte数组长度小于等于4
* byte数组是0-n表示高位到低位
*
* @param values
* @return
*/
public static int convertBytes4Int(byte[] values) {
int ret = 0;
int length = values.length > 4 ? 4 : values.length;
for (int n = 0; n < length; n++) {
ret += ((values[n] & 0xFF) << 8 * (3 - n));
}
return ret;
}
public static short convertBytes4Short(byte[] values) {
short ret = 0;
int length = 2;
for (int n = 0; n < length; n++) {
ret += ((values[n] & 0xFF) << 8 * (1 - n));
}
return ret;
}
/**
* 把int类型的数据转成一个byte
*
* @param value
* @return
*/
public static byte convertInt2Byte(int value) {
return (byte) (value & 0xFF);
}
/**
* 把byte转成int
*
* @param b
* @return
*/
public static int convertByte2Int(byte b) {
return b&0xFF;
}
/**
* 把字符串转换成byte数组。
* 规则:按照utf-8的方式,到ascii表里面找到单个字符对应的编码,比如a->0x61
*
* @param str
* @return
*/
public static byte[] convertString2Bytes(String str) {
return CommandUtil.convertInt2Bytes(Integer.parseInt(str));
}
public static String showByte2Hex(byte b) {
String string = Integer.toHexString(b & 0xFF);
if (string.length() <= 1) {
return "0" + string;
} else {
return string;
}
}
/**
* 按照低位到高位打印结果,如8888855->0x17 0xa2 0x87 0x0
*
* @param bytes
* @return
*/
public static String showByteArray2Hex(byte[] bytes) {
if (bytes == null || bytes.length <= 0) {
return "";
}
StringBuilder sb = new StringBuilder();
for (int n = 0; n < bytes.length; n++) {
sb.append(showByte2Hex(bytes[n])).append(" ");
}
return sb.toString();
}
/**
* @param origin
* @param startIndex
* @param from
*/
public static void mergeBytes(byte[] origin, int startIndex, byte[] from) {
for (int n = 0; n < from.length; n++) {
origin[startIndex++] = from[n];
}
}
/**测试*/
public static void main(String[] args) {
byte[] bs = CommandUtil.convertInt2Bytes(1234567890);
int ret = CommandUtil.convertBytes4Int(bs);
System.out.println(ret);
System.out.println(CommandUtil.showByteArray2Hex(CommandUtil.convertInt2Bytes(1234567890)));
bs = CommandUtil.convertString2Bytes("aa");
System.out.println(CommandUtil.showByteArray2Hex(bs));
}
}
JAVA ConvertUtil-字节,字节数组转换,合并,使用整合
最新推荐文章于 2024-08-24 04:21:16 发布