java - 如何将原始图像转换为带符号的 32 位图像

标签 java hex arrays signed endianness

我有一个使用 dd 命令创建的文件(原始文件)。我用bless打开了它,如下图所示:

Bless

现在我想从此文件中提取数据并获取 Signed 32 bit 下显示的内容(如果您看到图像 84 就是我想要的数字)。因此,我想以这种方式转换以下字符串:

10 00 00 00 --> 84
54 00 00 00 --> 70185301

为了进行此转换,我构建了以下程序,该程序打开文件,解码该行并将结果写入新文件中。

这是执行提取的代码段(@Duncan 帮助我创建了它):

try
  {
 
    File input = new File(inputFileField.getText());
    File output = new File(fileDirectoryFolder.getText() +"/"+ input.getName());

    byte[] buffer = new byte[8];         
    DataOutputStream out = new DataOutputStream(new FileOutputStream(output)); 
    DataInputStream in = new DataInputStream(new FileInputStream(input));

    int count = 0;        
    
    while (count < input.length() - 4) {

        in.readFully(buffer, 4, 4);
        String s= Long.toString(ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getLong());
        out.writeBytes( s+ " ");        
        count += 4;
     }
   }
   System.out.println("Done"); 
     
}
catch(FileNotFoundException e1){}

但是,我得到的结果是

10 00 00 00 --> 68719476736 
54 00 00 00 --> 360777252864

你明白我的问题出在哪里吗?

谢谢

最佳答案

String s= 
Integer.toString(
   ByteBuffer.wrap(buffer).order(ByteOrder.LITTLE_ENDIAN).getInt());

Long 有 8 个字节,您只想转换 4 个。

并且不要使用偏移量

in.readFully( buffer, 0, 4 );

$ echo $[0x1000000000]
68719476736
$ echo $[0x5400000000]
360777252864

这是由于读取时偏移了 4 个字节(不正确)造成的。

还有一个应该更正的:

 while (count < input.length() - 3) {

关于java - 如何将原始图像转换为带符号的 32 位图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24311583/

相关文章:

java - 空指针异常

c - 单元测试 : Compare Expected Result with hexadezimal

java - 如何使用 JAXB 将 null 值表示为空元素?

java - 什么是 NullPointerException,我该如何解决?

python - 如何将 int 转换为十六进制字符串?

arrays - 旋转 kotlin 数组

php - SQL Select where IN (array) 仅当找到数组中的第一项时才返回

c - 使用 C 程序解析 MIDI 文件时出现问题

java - 声明的对象变量给出 NullPointerException (Java)?

google-sheets - 在 Google 表格中查找默认填充颜色的颜色代码