打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
byte与int之间的互相转换
1.byte uses 1 byte while int uses4 bytes.

2. integer literals like "45" are of byte int not byte.
If you want a literal to be a byte, you have to
cast it: "(byte)45".

3. When values are promoted as part of an expression
or as parameters to a method call, they may be
promoted to int, but never to byte.

4. Many parts of the Java language used int, but none
of them use byte. For example, the length of an
array is an int.

/**
     * Convert  an int to a byte array
     *
     * @param value int
     * @return byte[]
     */

public static byte[] intToByteArray(int value) {
        byte[] b = new byte[4];
        for (int i = 0; i < 4; i++) {
            int offset = (b.length - 1 - i) * 8;
            b[i] = (byte) ((value >>> offset) & 0xFF);
        }
        return b;
    }



    /**
     * Convert the byte array to an int starting from the given offset.
     *
     * @param b The byte array
     * @param offset The array offset,如果byte数组长度就是4,则该值为0
     * @return The integer
     */
    public static int byteArrayToInt(byte[] b, int offset) {
        int value = 0;
        for (int i = 0; i < 4; i++) {
            int shift = (4 - 1 - i) * 8;
            value += (b[i + offset] & 0x000000FF) << shift;
        }
        return value;
    }
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
【Java】SubarrayUtils(查找子数组工具类)
byte[]数组和int之间的转换
整理:java整型数与网络字节序的 byte[] 数组转换关系
C#环形缓冲区(队列)完全实现
C#图片处理之:亮度和对比度的校正
C#之Socket操作类实例解析
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服