负数在java中的存储和读取过程

来源:互联网 发布:淘宝店服装拍摄 编辑:程序博客网 时间:2024/05/23 11:21

问题描述:

将-5存储在文本文件中,再读取出来显示到控制台;

预备知识:

1.在java中使用补码处理数字,而且byte(8)的数字在扩展成int(32)类型的时候,正数填充0,负数填充1;

2.负数的转变过程正数的原码,反码,补码,都一样;


解决步骤:

1.  -5(5)在byte类型中的表示是1000 0011(0000 0011) 当它扩展成int的时候会变成 11111111 11111111 11111111 11111011(00000000 00000000 00000000  00000011);

2.  

byte binaryInt = -5;
Path path = Paths.get("..");
try {
OutputStream out = new BufferedOutputStream(Files.newOutputStream(path, CREATE));
out.write(binaryInt);
out.flush();
out.close();
BufferedInputStream input = new BufferedInputStream(Files.newInputStream(path));
int i= input.read();
input.close();
System.out.println(i);
} catch (IOException ex) {

输出为 251

3.原因

第一步是看写入操作

jdk BufferedOutputStream write()源码

    public synchronized void write(int b) throws IOException {
        if (count >= buf.length) {
            flushBuffer();
        }
        buf[count++] = (byte)b;
    }

在写入操作的时候只是把11111111 11111111 11111111 11111011的后8位写入了文件中,这也就解释了文件中为什么是0xFB的原因了;


然后是读取操作

jdk InputStream read() 源码

    public synchronized int read() throws IOException {
        if (pos >= count) {
            fill();
            if (pos >= count)
                return -1;
        }
        return getBufIfOpen()[pos++] & 0xff;
    }

java中位运算会先将参与运算的数据类型转换成int,
证明了这一点;所以getBufIfOpen()[pos++]扩展成int数据类型时候是11111111 11111111 11111111 11111011,getBufIfOpen()[pos++] & 0xff就变成了11111111 11111111 11111111 11111011&00000000 00000000 00000000 11111111最后是251;

4.解决办法
int i= input.read()-256;就可以得到原值了;


1 0