Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert a single hex character to its byte value in java

Tags:

java

hex

I have a single hexadecimal character, say

char c = 'A';

What's the proper way of converting that to its integer value

int value =??; 
assert(a == 10);

Doesn't matter really for now if a is an int or a byte.

like image 223
nos Avatar asked Nov 27 '22 12:11

nos


2 Answers

i don't see why you should have to convert to string... in fact this is what parseInt uses:

public static int digit(char ch, int radix)

int hv = Character.digit(c,16);
if(hv<0)
    //do something else because it's not hex then.
like image 160
Victor Avatar answered Dec 21 '22 11:12

Victor


int value;
try {
    value = Integer.parseInt(Character.toString(c), 16);
}
catch (NumberFormatException e) {
    throw new IllegalArgumentException("Not a hex char");
}
like image 40
jqno Avatar answered Dec 21 '22 10:12

jqno