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

    原文网址:http://freewind886.blog.163.com/blog/static/661924642011810236100/

    最近在做些与编解码相关的事情,又遇到了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://zhidao.baidu.com/question/586106005.html

    1、string 转 byte[]

    String str = "Hello";
    byte[] srtbyte = str.getBytes();

    2、byte[] 转 string

    byte[] srtbyte;
    String res = new String(srtbyte);
    System.out.println(res);

    3、设定编码方式相互转换

    String str = "hello";
    byte[] srtbyte = null;
    try {
        srtbyte = str.getBytes("UTF-8");
        String res = new String(srtbyte,"UTF-8");
        System.out.println(res);
    } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

  • 相关阅读:
    javamail 利用qq邮箱做邮箱服务器,简单小demo
    apache tiles 页面模板的使用
    PHP中Cookie与Session的异同以及使用
    PHP二维数组--去除指定列含有重复项的数组
    PHP实现简单的双色球机选号码
    PHP常用的数学函数和字符串函数
    PHP日期函数
    PHP的操作符与控制结构
    PHP的变量作用域-常亮-全局变量-表单提交变量
    PHP四种输出语句
  • 原文地址:https://www.cnblogs.com/wi100sh/p/4548599.html
Copyright © 2011-2022 走看看