How can I read a file as unsigned bytes in Java?

How can I read a file in bytes in Java?

It is important to note that all bytes must be positive, i.e. negative range cannot be used.

Can this be done in Java, and if so, how?

I need to be able to multiply the contents of the file by a constant. I assumed that I could read bytes in BigInteger and then multiply, however, since some of the bytes are negative, I end up 12 13 15 -12, etc. And I'm stuck.

+5
source share
5 answers

, Java ... byte , -128 127 . , , , , #, "255", , "-1" Java. , .

EDIT: int . :

byte b = -1; // Imagine this was read from the file
int i = b & 0xff;
System.out.println(i); // 255

int, byte, .

FileInputStream , , FileChannel.

, ... , .

+15

unsigned API Java 8 Byte.toUnsignedInt. , .

int byte , (byte)value

+2

, 128 , . -128 127 0 255. ;)

, , Java , :

byte a = 0;
byte b = 1;

byte c = a | b;

, a | b .

byte c = (byte) a | b;

128 , .

+1

(, ​​ - ):

. , BigInteger, , , , 12 13 15 -12 .. .

BigInteger, [] ( ) BigInteger.

/**
 * reads a file and converts the content to a BigInteger.
 * @param f the file name. The content is interpreted as
 *   big-endian base-256 number.
 * @param signed if true, interpret the file content as two complement
 *                  representation of a signed number.
 *               if false, interpret the file content as a unsigned
 *                  (nonnegative) number.
 */
public static BigInteger fileToBigInteger(File f, boolean signed)
    throws IOException
{
    byte[] array = new byte[file.length()];
    InputStream in = new FileInputStream(file);
    int i = 0; int r;
    while((r = in.read(array, i, array.length - i) > 0) {
        i = i + r;
    }
    in.close();
    if(signed) {
        return new BigInteger(array);
    }
    else {
        return new BigInteger(1, array);
    }
}

BigInteger ( toByteArray()).

, - , toByteArray(), - . , .

" ". - ?

+1

, unsigned byte [0... 255] :

Reader bytestream = new BufferedReader(new InputStreamReader(
        new FileInputStream(inputFileName), "ISO-8859-1"));
int unsignedByte;
while((unsignedByte = bytestream.read()) != -1){
    // do work
}

, , , ISO 8859-1 .

0

All Articles