简体   繁体   中英

android how to get unsigned byte array from getinputstream

I use getInputStream from socket ; however, when I want to convert my byte array to long it will get the wrong number. When I used debug mode to see each value of the byte array, I found the value would be signed. How can I convert my signed byte array to unsigned array? Or I got the wrong sense that the problem was not related to the signed problem. If there's any information insufficient, please tell me. Thanks.

Below is my code:

InputStream inputStream = socket.getInputStream();

byte[] fileNameBytes = new byte[8];
byte[] totalLengthBytes = new byte[8];
try {
    inputStream.read(fileNameBytes);
    inputStream.read(totalLengthBytes);
} catch (Exception ex) {
    Log.e("Error in InputStream: " + ex.getMessage());
}

totalLength = byteArrayToLong(totalLengthBytes);

java has issues with signed/unsigned. Namely, no unsigned. When I've need to upload raw bytes to a C# web service that expects bytes to be unsigned (ie 0 to 255 vs -127 to +127), I've used code I'm not proud of, that looks like:

        List<Integer> l = new ArrayList<Integer>();
        if (bytearray != null) {
            for (int i = 0; i < bytearray.length; ++i) 
            {
                l.add(Integer.valueOf((char) bytearray [i]) & 0x00FF);
            }
        }

Where bytearray is a byte[]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM