簡體   English   中英

如何添加兩個包含十六進制數字的字符串而不將它們轉換為 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";

我知道這個問題已經被問到如何在 Java 中減去或添加兩個十六進制值,但答案對我不起作用,因為它們都涉及到 int 的轉換。

你可以這樣做:

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

將您的代碼更改為:

String hex1="0xf27f2029f9c103f77be78b9591c1ab27167858d27d789cd3ea8a270c67ea5d91";
int hex2=0x1;
string hex2="0x1";

您需要“”來輸入字符串值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM