Java【解決方法】Byte[]、UByte[]的問題 Byte有負號
No Comments

更新於 2016-01-06 18:37:17

    String str = "這是測試!ABC123.";
    byte[] bytes = {};
    try {
        bytes = str.getBytes("UTF-8");
    }catch(Exception ex){
    }
    for(int i=0;i<bytes.length;i++){
        System.out.println(bytes[i]);
    }
    System.out.println(bytes);

我們都知道,其實,Java裡面本身並不支援Ubyte。若真要使用差不多的功能,建議可以改用Short。

Ubyte就是沒有負號,而Byte就是可能會有負號。跟轉成二進制之後的高位補數與否有關係的樣子。

在此提供解決方法。直接看Code。

    //將字串以UTF8編碼轉成Ubyte[](實際上是short[]型別)
    public static short[] StringtoUByte(String str) {
        byte[] bytes = {};
        try {
            bytes = str.getBytes("UTF-8");
        }catch(UnsupportedEncodingException ex){

        }
        return BytetoUByte(bytes);
    }

    //將Ubyte[]以UTF8編碼轉成字串(實際上是short[]型別轉成字串)
    public static String UBytetoString(short[] ubytes) {
        byte[] bytes = UBytetoByte(ubytes);
        String str = "";
        try{
            str = new String(bytes,"UTF-8");
        }catch (Exception ex){

        }
        return str;
    }

    //將Ubyte[]轉成byte[](將short[]轉成byte[])
    public static byte[] UBytetoByte(short[] ubytes) {
        byte[] bytes = new byte[ubytes.length];
        for(int i=0;i<bytes.length;i++){
            bytes[i]=signedToBytes(ubytes[i]);
        }
        return bytes;
    }

    //將byte[]轉成Ubyte[](將byte[]轉成short[])
    public static short[] BytetoUByte(byte[] bytes) {
        short[] ubytes = new short[bytes.length];
        for(int i=0;i<bytes.length;i++){
            ubytes[i]=unsignedToBytes(bytes[i]);
        }
        return ubytes;
    }

    //將byte轉成Ubyte(將byte轉成short)
    public static short unsignedToBytes(byte b) {
        return (short)(b & 0xFF);
    }

    //將Ubyte轉成byte(將int轉成byte)
    public static byte signedToBytes(int b) {
        return ((byte)(b & 0xFF));
    }

可能看官們都注意到,byte轉ubyte都是 一樣的寫法。==> b & 0xFF

只是給他加個二進位負號而已,再加一個負號又變回原樣了。So,解釋完畢,上面的代碼自行取用吧。


This entry was posted in Java, Note By Weil Jimmer.

About Weil Jimmer

Hi! Everyone! My name is Weil Jimmer. This is my personal blog. I'm a webmaster of this site. I hope the site will be popular. Now, Let's go! Enjoy gaining more knowledge.
More Details About Me : https://weils.net/profile.php


Leave a message.

Only the first 10 comment will show.