使用位运算符将十进制转换为十六进制的 Java 代码

问题描述 投票:0回答:1

我有这段代码可以将十进制转换为十六进制,但我需要它才能处理大于 255 的数字。

        int v = 13;
        String hexV = ""; 
        for (int i=0; i<2; i++) { 
            int rem = v & 15;
            v = (byte)(v >> 4); 
            hexV = "0123456789ABCDEF".charAt(rem) + hexV;
        }
        System.out.println("V: " + hexV);

此代码适用于 255 以内的数字,但我需要它适用于更大的范围。鉴于此代码,我如何更改它以适用于更大的数字?特别是范围 (-524288 - 524287)。我不想使用 toHexString 或类似的方法,我只是想使用我给出的代码。

我试过从 i 改变循环<2 to i<3 up to i<6 to accommodate for the extra places in the hexadecimal conversion but the result is never accurate. Usually the last two digits are correct and the rest of it isn't.

java loops hex bitwise-operators
1个回答
0
投票

运行循环直到

v
变成
0
并移除 cast 到
byte
.

String hexV = ""; 
while (v > 0) { 
    int rem = v & 15;
    v >>= 4; 
    hexV = "0123456789ABCDEF".charAt(rem) + hexV;
}
最新问题
© www.soinside.com 2019 - 2025. All rights reserved.