【问题标题】:Binary Int Array to ASCII Equivalent in JavaJava 中二进制 Int 数组到 ASCII 等价物
【发布时间】:2014-06-10 06:51:20
【问题描述】:

我在这里搜索了一段时间,似乎没有什么可以帮助我完成我的任务。我正在尝试手动转换一个包含二进制代码的 int 数组,进行十进制转换,然后将其转换为 char 以获得等效的 ascii。我已经开始了一些事情,但是当我打印出来时,我得到 -591207182 作为消息,这显然是不正确的。我的程序在下面。我在编写和理解 Java 方面相当新手,因此非常感谢最有效且易于理解的路线。

class DecodeMessage
{
    public void getBinary(Picture secretImage)
    {
    Pixel pixelObject = null;
    Color pixelColor = null;
    int [] binaryInt = new int[secretImage.getWidth()];
    int x = 0;


      int redValue = 0;
        while(redValue < 2)
        {         
            Pixel pixelTarget = new Pixel(secretImage,x,0);
            pixelColor = pixelTarget.getColor();
            redValue = pixelColor.getRed();
            binaryInt[x] = redValue;
            x++;
        }
    }
        public void decodeBinary(int [] binary)
        {
        int binaryLen = binary.length;
        long totVal = 0;
        int newVal = 0;
        int bitVal = 0;
        long preVal = 0;
        long base = 2;

        for(int x = binaryLen - 1; x >= 0; x--)
        {
            bitVal = binary[x];
            preVal = bitVal * base;
            totVal += preVal;
            base = base * 2;
        }

        System.out.println(totVal);
     }
}
public class DecodeMessageTester
{
    public static void main(String[] args)
    {
        Picture pictureObj = new Picture("SecretMessage.bmp");
        pictureObj.explore();
        DecodeMessage decode = new DecodeMessage();
        decode.getBinary(pictureObj);
        int[] bitArray = {0,1,1,0,0,0,1,0,0,1,1,0,1,0,0,1,0,1,1,0,1,1,1,0,0,1,1,0,0,0,0,1,0,1,1,1,0,0,1,0,0,1,1,1,1,0,0,1};
        decode.decodeBinary(bitArray);
    }
}

【问题讨论】:

  • char 的演员在哪里?
  • 从二进制中尝试String decimalString = new BigInteger("0010",2).toString(10));十进制。

标签: java arrays binary int


【解决方案1】:

您的问题是您试图将所有 48 位压缩到一个 int 中。但是,正如http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html 所述,Java 中的int 只能保存 32 位,因此您的数字会溢出。尝试将basepreValtotVal 更改为long,它可以容纳64 位。

当然,如果您需要超过 64 位(或者实际上是 63,因为最后一位是符号位),您将无法使用原始数字数据类型来保存它。

【讨论】:

  • 这有点帮助,现在不是负值......当终端窗口打印它时,我现在有 216409925936370 代替。
猜你喜欢
  • 2014-04-24
  • 2011-02-05
  • 2016-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-10-21
  • 2015-06-17
相关资源
最近更新 更多