Source From Here
Question
I would like to convert a hex string to a binary string. For example, Hex 2 is 0010. Below is the code:
However this only works for Hex 0 - 9; it won't work for Hex A - F because it uses int. Can anyone enhance it?
How-To
You need to tell Java that the int is in hex, like this:
Another approach is to used exist library. For example,
flib:
Execution result:
Question
I would like to convert a hex string to a binary string. For example, Hex 2 is 0010. Below is the code:
- String HexToBinary(String Hex)
- {
- int i = Integer.parseInt(Hex);
- String Bin = Integer.toBinaryString(i);
- return Bin;
- }
How-To
You need to tell Java that the int is in hex, like this:
- String hexToBinary(String hex) {
- int i = Integer.parseInt(hex, 16);
- String bin = Integer.toBinaryString(i);
- return bin;
- }
- package test;
- import flib.util.HexByteKit;
- public class Test {
- public static void main(String[] args) {
- String hexStrs[] = { "12F", "3E" };
- try {
- for (int i = 0; i < hexStrs.length; i++) {
- String hxs = hexStrs[i];
- String obs = HexByteKit.Hex2Bin(hxs);
- System.out.printf("%s(%d)=%s\n", hxs,
- Integer.parseInt(hxs, 16), obs);
- }
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
沒有留言:
張貼留言