有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何将字节存储在整数中

在java的InputStream类中。io.*套餐:

int read()引发IOException

read()返回ByTestStream类下的字节,但它以整数形式存储,没有任何错误

为什么会这样??它是如何发生的。还可以帮我做内存分配设计


共 (1) 个答案

  1. # 1 楼答案

    javadoc给出了上下文,它说:

    "Reads the next byte of data from the input stream. The value byte is returned as an int in the range 0 to 255. If no byte is available because the end of the stream has been reached, the value -1 is returned."

    在引擎盖下,read方法要么返回一个字节,要么流处于EOF位置。因此,返回值可以包含257种可能的状态,而且(显然)这些状态不适合byte。API通过返回一个int来处理这个问题,按照我上面引用的javadoc摘录指定的编码

    我还没看过代码,但我想大概是这样的:

        if (eof) {
            return -1;
        } else {
            // Casting to an int sign extends to 32 bits,
            // and we then take the bottom 8 bits.
            return ((int) someByte) & 0xff;
        }
    

    当你得到结果时,你需要这样做:

        int res = is.read();
        if (res == -1) {
            // handle EOF case ...
        } else {
            byte b = (byte) res;
            // handle the byte ...
        }
    

    Help me the memory allocation design also.

    没有内存分配问题。byteint类型是基本类型