[英]Binary Int Array to ASCII Equivalent in Java
我在這里搜索了一段時間,似乎沒有任何幫助。 我正在嘗試手動轉換其中具有二進制代碼的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);
}
}
您的問題是您試圖將所有48位壓縮為一個int
。 但是,正如http://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html所述,Java中的int
只能容納32位,因此您的數字會溢出。 嘗試將base
, preVal
和totVal
為long
,可以容納64位。
當然,如果您需要64位以上(或者實際上是63位,因為最后一位是符號位),則將無法使用原始數字數據類型來保存該位。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.