简体   繁体   English

Java中与ASCII等效的二进制整数数组

[英]Binary Int Array to ASCII Equivalent in Java

I searched around here for awhile and nothing seems to help me with my assignment. 我在这里搜索了一段时间,似乎没有任何帮助。 I'm trying to convert an int array that has binary code in it manually, do the decimal conversion and then cast it as a char to get the ascii equivalent. 我正在尝试手动转换其中具有二进制代码的int数组,进行十进制转换,然后将其强制转换为char以获取等价的ascii。 I have something started, but when I print it out, I get -591207182 as the message, which obviously isn't correct. 我开始了一些工作,但是当我打印出来时,得到的消息是-591207182,这显然是不正确的。 I have my program down below. 我的程序在下面。 I'm fairly novice at writing and understanding Java, so the most efficient and easy to understand route would be much appreciated. 我对编写和理解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);
    }
}

Your problem is that you're trying to squeeze all 48 bits into one int . 您的问题是您试图将所有48位压缩为一个int However, as http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html states, an int in Java can only hold 32 bits, so your numbers overflow. 但是,正如http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html所述,Java中的int只能容纳32位,因此您的数字会溢出。 Try changing base , preVal and totVal to long , which can hold 64 bits. 尝试将basepreValtotVallong ,可以容纳64位。

Of course, if you need more than 64 bits (or 63 actually because the last bit is the sign bit), you will not be able to use a primitive number datatype to hold that. 当然,如果您需要64位以上(或者实际上是63位,因为最后一位是符号位),则将无法使用原始数字数据类型来保存该位。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM