본문

HEX값을 2의보수로 계산하여 Decimal로 출력하기

반응형

# HEX값을 2의보수로 계산하여 Decimal로 출력하기

# 2's complement hex number to decimal in java


-. HEX String을 2의보수로 계산하여 Decimal로 출력하는 소스

-. Hex to Decimal converter: https://www.rapidtables.com/convert/number/hex-to-decimal.html


1. Soruce
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
package com.aimir.fep.bypass.sts.cmd;
 
import java.math.BigInteger;
 
public class Test {
 
    public static void main(String[] args) {
        String hexString = "FAA2A4E0";
        
        // 2's complement hex number to decimal
        long resultDecial = Long.parseLong(hexToDec(hexString).toString());
        
        System.out.println("resultDecial: " + resultDecial);
    }
    
    public static Number hexToDec(String hex)  {
           if (hex == null) {
              throw new NullPointerException("hexToDec: hex String is null.");
           }
 
           // You may want to do something different with the empty string.
           if (hex.equals("")) { return Byte.valueOf("0"); }
 
           // If you want to pad "FFF" to "0FFF" do it here.
 
           hex = hex.toUpperCase();
 
           // Check if high bit is set.
           boolean isNegative =
              hex.startsWith("8") || hex.startsWith("9") ||
              hex.startsWith("A") || hex.startsWith("B") ||
              hex.startsWith("C") || hex.startsWith("D") ||
              hex.startsWith("E") || hex.startsWith("F");
 
           BigInteger temp;
 
           if (isNegative) {
              // Negative number
              temp = new BigInteger(hex, 16);
              BigInteger subtrahend = BigInteger.ONE.shiftLeft(hex.length() * 4);
              temp = temp.subtract(subtrahend);
           } else {
              // Positive number
              temp = new BigInteger(hex, 16);
           }
 
           // Cut BigInteger down to size.
           if (hex.length() <= 2) { return (Byte)temp.byteValue(); }
           if (hex.length() <= 4) { return (Short)temp.shortValue(); }
           if (hex.length() <= 8) { return (Integer)temp.intValue(); }
           if (hex.length() <= 16) { return (Long)temp.longValue(); }
           
           return temp;
        }
 
}
 


2. Result

1
2
3
4
5
6
7
8
9
10
11
12
13
14
String hexString = "0004941E";
resultDecial: 300062
 
String hexString = "00000000";
resultDecial: 0
 
String hexString = "FFFFD8FB";
resultDecial: -9989
 
String hexString = "FFFEC788";
resultDecial: -79992
 
String hexString = "FAA2A4E0";
resultDecial: -90004256




P.S. https://stackoverflow.com/questions/6699275/2s-complement-hex-number-to-decimal-in-java

반응형

공유

댓글