【转】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();
}

posted on 2015-06-03 11:08  wi100sh  阅读(15235)  评论(0编辑  收藏  举报

导航