字节与字符相互编码 强制编码方式 java

public class BruteForceCoding {

private static byte byteVal = 101;
private static short shortVal = 10001;
private static int intVal = 100000001; 
private static long longVal = 1000000000001L;

private final static int BSIZE = Byte.SIZE / Byte.SIZE;
private final static int SSIZE = Short.SIZE / Byte.SIZE;
private final static int ISIZE = Integer.SIZE / Byte.SIZE;
     private final static int LSIZE = Long.SIZE / Byte.SIZE;
     
private final static int BYTEMASK = 0xFF; // 8字节
 
public static String byteArrayToDecimalString(byte[] bArray) {
StringBuilder rtn = new StringBuilder();
for (byte b : bArray) {
rtn.append(b & BYTEMASK).append(" ");
}
return rtn.toString();
}

//编码
public static int encodeIntBigEndian(byte[] dst, long val, int offset, int size) {
for (int i = 0; i < size; i++) {
dst[offset++] = (byte) (val >> ((size - i - 1) * Byte.SIZE));
}
return offset;
}


//解码
public static long decodeIntBigEndian(byte[] val, int offset, int size) {
long rtn = 0;
for (int i = 0; i < size; i++) {
rtn = (rtn << Byte.SIZE) | ((long) val[offset + i] & BYTEMASK);
}
return rtn;
}

public static void main(String[] args) {
byte[] message = new byte[BSIZE + SSIZE + ISIZE + LSIZE];

int offset = encodeIntBigEndian(message, byteVal, 0, BSIZE);
offset = encodeIntBigEndian(message, shortVal, offset, SSIZE);
offset = encodeIntBigEndian(message, intVal, offset, ISIZE);
encodeIntBigEndian(message, longVal, offset, LSIZE);
System.out.println("Encoded message: " + byteArrayToDecimalString(message));


long value = decodeIntBigEndian(message, BSIZE, SSIZE);
System.out.println("Decoded short = " + value);
value = decodeIntBigEndian(message, BSIZE + SSIZE + ISIZE, LSIZE);
System.out.println("Decoded long = " + value);


//转换
offset = 4;
value = decodeIntBigEndian(message, offset, BSIZE);
System.out.println("Decoded value (offset " + offset + ", size " + BSIZE + ") = " + value);
byte bVal = (byte) decodeIntBigEndian(message, offset, BSIZE);
System.out.println("Same value as byte = " + bVal);
}


}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值