如何添加两个包含十六进制数字的字符串而不将它们转换为 int?
How can I add two Strings containing hexadecimal-numbers without converting them to int?
我在字符串中有一个十六进制数,它太大而无法转换为 int 和 long,我想添加另一个十六进制数的值。
假设我有这个号码:
String hex1 = "0xf27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d91";
并想补充:
int hex2 = 0x1; or String hex2 = "0x1";
我知道这个问题已经有人问过了 How to subtract or add two hexadecimal value in java 但答案对我不起作用,因为它们都涉及转换为 int。
将您的代码更改为:
String hex1="0xf27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d91";
int hex2=0x1;
string hex2="0x1";
您需要“”才能为字符串输入值。
您可以按照以下方式进行:
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
String hex1 = "0xf27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d91";
String hex2 = "0x1";
System.out.println(
"In decimal: " + new BigInteger(hex1.substring(2), 16).add(new BigInteger(hex2.substring(2), 16)));
System.out.println("In hexdecimal: "
+ new BigInteger(hex1.substring(2), 16).add(new BigInteger(hex2.substring(2), 16)).toString(16));
}
}
输出:
In decimal: 109684320921920394042076832992416841330182602685967688614501993994243850001810
In hexdecimal: f27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d92
我在字符串中有一个十六进制数,它太大而无法转换为 int 和 long,我想添加另一个十六进制数的值。 假设我有这个号码:
String hex1 = "0xf27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d91";
并想补充:
int hex2 = 0x1; or String hex2 = "0x1";
我知道这个问题已经有人问过了 How to subtract or add two hexadecimal value in java 但答案对我不起作用,因为它们都涉及转换为 int。
将您的代码更改为:
String hex1="0xf27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d91";
int hex2=0x1;
string hex2="0x1";
您需要“”才能为字符串输入值。
您可以按照以下方式进行:
import java.math.BigInteger;
public class Main {
public static void main(String[] args) {
String hex1 = "0xf27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d91";
String hex2 = "0x1";
System.out.println(
"In decimal: " + new BigInteger(hex1.substring(2), 16).add(new BigInteger(hex2.substring(2), 16)));
System.out.println("In hexdecimal: "
+ new BigInteger(hex1.substring(2), 16).add(new BigInteger(hex2.substring(2), 16)).toString(16));
}
}
输出:
In decimal: 109684320921920394042076832992416841330182602685967688614501993994243850001810
In hexdecimal: f27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d92