View Full Version : JAVA -- isHex(String inp) Funtion
JustnK101
09-18-2005, 12:51 PM
Is there a built in fucntion in Java that checks if every character in a string is a valid hex character?
I.E:
0,1,2,3,4,5,6,7,8,9,A,B,C,D,E,F
I looked and could not locate anything?
If there inst a pre-defined function, can somebody write me a real quick and dirty function? Thanks!
nikkiH
09-19-2005, 05:53 PM
Just use Pattern class and a regular expression.
Roelf
09-19-2005, 08:04 PM
Quick and dirty huh:
Why test every character, why not the entire string:
public boolean isHex (String in) {
boolean ret;
try {
// try to parse the string to an integer, using 16 as radix
int t = Integer.parseInt(in, 16);
// parsing succeeded, string is valid hex number
ret = true;
} catch (NumberFormatException e) {
// parsing failed, string is not a valid hex number
ret = false;
}
return (ret);
}
KeZZeR
09-20-2005, 12:00 PM
Another way that I learnt not long ago (just for reference, this doesn't mean you have to use it)
final static String CHARACTERS = "0123456789ABCDEF";
public boolean isHex(char ch) {
return CHARACTERS.indexOf(ch) > -1;
}
So it passes the character in to the method and checks if it exists in the constant if it exists. It's quite a smart way of doing it, if the character exists it'll return the index position of that character which can be anything from 0 upwards :)
vBulletin® v3.8.2, Copyright ©2000-2012, Jelsoft Enterprises Ltd.