Search code examples
javastringhex

check hex string contains only hex bounded values


How to check a given hex string contains only hex number. is there is any simple method or any java library for the same?i have string like "01AF" and i have to check string only contains hex range values,for that what i am doing now is take the string and then split the string and then converted it to appropriate format then make a check for that value.is there is any simple method for that?


Solution

  • try
    {
        String hex = "AAA"
        int value = Integer.parseInt(hex, 16);  
        System.out.println("valid hex);
     }
     catch(NumberFormatException nfe)
     {
        // not a valid hex
        System.out.println("not a valid hex);
     }
    

    This will throw NumberFormatException if the hex string is invalid.

    Refer the documentation here