gpt4 book ai didi

java - 如何向后读取二进制字符串数组,然后转换为十进制 int 变量? (没有解析)

转载 作者:行者123 更新时间:2023-12-02 10:15:16 25 4
gpt4 key购买 nike

我不明白如何将以下代码编码到程序中:向后读取字符串二进制数组。检查反转的二进制数组是否为 1(我假设是 if 语句)。为二进制中的每个 1 分配位值。利用 math.pow 获取每个 1 的十进制值。添加所有 Activity 位。

我的程序需要执行以下操作:打开文本文件(已完成)文本文件包含:

 (33CDAEFFAD)  
(032DAE01AD)
(196CDAEFC0)
(21A00D0000)
(100CDAEFFA)
(F3ABCDEFAB)
(29A0EDF301)
(3ABCDEFABC)

读取每个十六进制(已完成)-->
将十六进制值转换为二进制值(已完成)-->
将二进制值转换为十进制值(LOST)

public static String[] hexToBinary () throws IOException //converts from 
hex to binary
{
Scanner inFile = new Scanner(new File("RAMun3"));

String result[] = new String[8]; //created array to hold binary values
String bValue;
String x = "";
String y = "";
int counter = 0;

while (inFile.hasNextLine() && counter <= 7) //reads lines from text
file && stops array from
going out of bounds
{
String line = inFile.nextLine();
Scanner input = new Scanner(line);
String hex = input.next();

for (int i = 0; i < hex.length(); i++) //for loop to convert hex
digits to binary
{
char hexC = hex.charAt(i);
switch (hexC)
{
case ('0'):
bValue = "0000";
break;
case ('1'):
bValue = "0001";
break;
case ('2'):
bValue = "0010";
break;
case ('3'):
bValue = "0011";
break;
case ('4'):
bValue = "0100";
break;
case ('5'):
bValue = "0101";
break;
case ('6'):
bValue = "0110";
break;
case ('7'):
bValue = "0111";
break;
case ('8'):
bValue = "1000";
break;
case ('9'):
bValue = "1001";
break;
case ('A'):
bValue = "1010";
break;
case ('B'):
bValue = "1011";
break;
case ('C'):
bValue = "1100";
break;
case ('D'):
bValue = "1101";
break;
case ('E'):
bValue = "1110";
break;
case ('F'):
bValue = "1111";
break;
default:
bValue = "N/A";
break;
}
x = bValue;
y += x;
}
result[counter] = y;
counter++;
y = "";
}
for (int t = 0; t < result.length; t++)
{
System.out.println(result[t]);
}
return result;
}

public static void reverseResult(String[] y) //Attempt at code for
reversing array
{
for (int i = y.length-1; i>=0; i--)
{
System.out.print(y[i]+" ");
}
}

public static int binToDecimal (){}

public static void main (String args[]) throws IOException //main
{
readFromFile();
hexToBinary();
binToDecimal();
}

}

转换后的预期输出:

222494130093 -- 13651280301 -- 109200469952 -- 144419127296 -- 68935151610 -- 1046559453099 -- 178793607937 -- 252276832956

最佳答案

反转结果中的每个字符串后:

public static int binToDecimal (){
for(String bin:result){
int dec=0;
for(int i=0;i<bin.length;i++){
dec+=Math.pow(2,i)*(bin.charAt(i)-'0');
}
println("" + dec);
}
}

使用您提到的“if”语句:

 public static int binToDecimal (){
for(String bin:result){
int dec=0;
for(int i=0;i<bin.length;i++){
if('1' == bin.charAt(i)){
dec+=Math.pow(2,i);
}
}
println("" + dec);
}
}

关于java - 如何向后读取二进制字符串数组,然后转换为十进制 int 变量? (没有解析),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54730096/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com