首页 > 解决方案 > 在 Java 中转换 int -> ascii -> int 时遇到问题

问题描述

我编写了这些函数以使用尽可能少的字节数将 int 值写入文件。但是由于某种原因,一行正在读取错误的值(见评论)。


File f = new File("data.txt");
RandomAccessFile raf = new RandomAccessFile(f, "rw");

raf.writeBytes(toByte(4321,3)); // convert 4321 to ascii
raf.seek(0);
System.out.println(fromByte(raf.readLine())); // convert back

// convert integer to ascii String for i < 16,777,216
// let b=1 for i<256, b=2 for i<256*256, b=3 for i<256*256*256
private static String toByte(int i, int b){
    if (b==3) // 3 bytes
        return "" + (char)(i/65536) + (char)(i%65536/256) + (char)(i%256);
    if (b==2) // 2 bytes
        return "" + (char)(i/256) + (char)(i%256);
    else      // 1 byte
        return "" + (char)i;
}

// convert ascii string to integer for s.length = {1,2,3} 
private static int fromByte(String s){
    int i = 0;
    if (s.length()==3)
        i = (int)s.charAt(0)*65536 + 
            (int)s.charAt(1)*256 + 
            (int)s.charAt(2);//------------> 65533? should be 225!
    else if (s.length()==2)
        i = (int)s.charAt(0)*256 + 
            (int)s.charAt(1);
    else
        i = (int)s.charAt(0);
    return i;
}

输出是 69629,但应该是 4321。

标签: javaintascii

解决方案


推荐阅读