java数据类型|字节转换

在数据类型相互转换

在转换中需要了解大端小端模式:
大端模式:数据的高位存储在内存的低字节。
小端模式:数据的地位存储在内存的低字节。

例如:数据 0x12345678 大小端模式中byte数据存储 如下:

模式数据值
大端模式{0x12,0x34,0x56,0x78}
小端模式{0x78,0x56,0x34,0x12}
  1. jdk封装 int|byte 相互转换
public void intToBytes(int value){
    // int 需要 4 byte, 默认是大端(ByteOrder.BIG_ENDIAN)
    return ByteBuffer.allocate(4).putInt(value).array();
}
public void bytesToInt(){
    byte[] byteArray = new byte[] {00, 00, 00, 01};
    return ByteBuffer.wrap(bytes).getInt();
}
  1. 自己封装 int|byte 类型转换
// 大端的解析方式
public int byteToIntBig(byte[] bytes){
    return (bytes[0] & 0xFF) << 24) | 
           ((bytes[1] & 0xFF) << 16) | 
           ((bytes[2] & 0xFF) << 8) | 
           ((bytes[3] & 0xFF);
}
public byte[] intToByteBig(int value){
    return new byte[]{(byte)(value >> 24),(byte)(value >> 16),(byte)(value >> 8),(byte)value};
}
// 小端解析方式
public int byteToIntLittle(byte[] bytes){
    return ((bytes[0] & 0xFF) |
            ((bytes[1] & 0xFF) << 8) |
            ((bytes[2] & 0xFF) << 16)|
            (bytes[3] & 0xFF) << 24);
}
public byte[] intToByteLittle(int value){
    return new byte[]{(byte)value,(byte)(value >> 8),(byte)(value >> 16),(byte)(value >> 24)};
}
  1. short|byte 相互转换
public bytes shortToByte(short value) {
    byte[] bytes = new byte[2];
    byte[0] = (byte) (0xff & (value >> 8))
    byte[1] = (byte) (0xff & value)
    return bytes;
}
  1. 对位的操作
/**
 * 获取指定位上的数值(注意index的值为要去的某一位上的数据值)
 * @param num:要获取二进制值的数
 * @param index:倒数第一位为0,依次类推
 */
public int getPositionValue(int num, int index){
    return (num & (0x1 << index)) >> index;
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值