zoukankan      html  css  js  c++  java
  • java中byte, int的转换

    最近在做些与编解码相关的事情,又遇到了byte和int的转换,看着那些关于反码、补码的说明依旧头疼,还是记下些实用的方法吧。
    int -> byte
    可以直接使用强制类型转换: byte b = (byte) aInt;
    这个操作是直接截取int中最低一个字节,如果int大于255,则值就会变得面目全非了。
    对于通过InputStream.read()获取的int,可采用这个方法将值还原。

    byte -> int
    这里有两种情况,一种是要求保持值不变,例如进行数值计算,可采用强制类型转换:int i = (int) aByte;
    另一种是要求保持最低字节中各个位不变,3个高字节全部用0填充,例如进行编解码操作,
    则需要采用位操作:int i = b & 0xff;

    int InputStream.read()
    该函数返回一个int类型,范围从0至255,如果到达流末尾,返回-1。通过ByteArrayInputStream的源码可以看到是如何从byte转到int
    public synchronized int read() {
        return (pos < count) ? (buf[pos++] & 0xff) : -1;
    }

    int <-> byte[]
    代码转自:java int 与 byte转换 
    public static byte[] toByteArray(int iSource, int iArrayLen) {
        byte[] bLocalArr = new byte[iArrayLen];
        for (int i = 0; (i < 4) && (i < iArrayLen); i++) {
            bLocalArr[i] = (byte) (iSource >> 8 * i & 0xFF);
        }
        return bLocalArr;
    }

    // 将byte数组bRefArr转为一个整数,字节数组的低位是整型的低字节位
    public static int toInt(byte[] bRefArr) {
        int iOutcome = 0;
        byte bLoop;

        for (int i = 0; i < bRefArr.length; i++) {
            bLoop = bRefArr[i];
            iOutcome += (bLoop & 0xFF) << (8 * i);
        }
        return iOutcome;
    }

    转自: http://freewind886.blog.163.com/blog/static/661924642011810236100/

  • 相关阅读:
    Less资源汇总
    Less函数说明
    Less使用说明
    Less 简介
    tomcat-users.xml 配置
    java project打包生成jar包(通用)
    5分钟理解String的'+'的性能及原理
    字符串"+"操作的原理
    Shell脚本实现对文件编辑
    mysql关于聚集索引、非聚集索引的总结
  • 原文地址:https://www.cnblogs.com/dracohan/p/4513574.html
Copyright © 2011-2022 走看看