【问题标题】:Getting signed short values when I wanted to write out unsigned short values当我想写出无符号短值时获取有符号短值
【发布时间】:2014-11-10 09:06:00
【问题描述】:

使用此处提供的解决方案 -Java input and output binary file byte size are not matching after transformation 我将一个二维数组写入磁盘,其中包含无符号短裤。当我通过读取该文件的值来检查它们时,我仍然看到有符号值,即负值。代码有什么错误?

fos = new FileOutputStream(destFile);
short[][] data = getData(); //defined in another class
if (ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN)
 {
   for (int i = 0;i<1200;i++)
    {
      for (int j = 0; j <1200;j++)
        {      
          fos.write((data[i][j] >> 8) & 0xFF);
          fos.write(data[i][j] & 0xFF);
        }
    }
 }
 else
     {
       for (int i = 0;i<1200;i++)
         {
          for (int j = 0; j <1200;j++)
           {
             fos.write(data[i][j] & 0xFF);
             fos.write((data[i][j] >> 8) & 0xFF);

            }
         }     
     }

【问题讨论】:

    标签: java unsigned short


    【解决方案1】:

    Java 没有无符号短数据类型,但不用担心,代码可以正常工作。有符号和无符号的位模式相同,区别在于第一位的解释方式。如果你想要一个无符号的短值,你可以使用 AND 运算符:

    int unsignedValue = signedShortValue & 0xFFFF;
    

    【讨论】:

    • Java创建的文件会被一个C程序读取,需要你指定输出数据的符号。在 C 程序的输入文件中,我说的是“无符号”吗?
    • 是的,在 C 中你可以使用unsigned
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-18
    • 1970-01-01
    相关资源
    最近更新 更多