java - 在 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。
解决方案
推荐阅读
- python - 框架和keras模型
- swift - 如何在 Swift 中的 png 图像后面添加一个 Circle()
- android - Android xml 布局显示为灰色
- c# - Intellocked.Exchange 而不是 ReaderWriterLockSlim
- java - 如何将数据传递给 Platform.runLater
- discord - discord.py 删除所有玩家的所有角色
- notifications - Swift UI 2.0:如何设置此通知?
- sql - Oracle sql中特殊字符<和>的转义
- java - 计算给定列表的 n 个幂集
- azure-cosmosdb - Cosmos DB 数据建模以优化搜索