Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie
Hi there,
There is an issue with role permissions that is being worked on at the moment.
If you are having trouble with access or permissions on regional forums please post here to get access: https://www.boards.ie/discussion/2058365403/you-do-not-have-permission-for-that#latest

A doozie of a String - int casting question (java)

  • 21-02-2005 4:48pm
    #1
    Registered Users, Registered Users 2 Posts: 2,323 ✭✭✭


    hey guys,

    I'm parsing a text file for a hexidecimal value in java. unfortunately the only way i can get the hex value is in String format. and because its in hex the parseInt method wont work cos its an invalid number format (basically the x fecks things up. i cant take it in as a TT_NUMBER because of the x, and Streamtokenizer takes everything after the x as a TT_WORD. so i get an nval 0 and a sval x01 instead of 0x01.). Does anyone know how to extract it as an integer or how i can convert it to an int? been looking at regex but i havent found out how it will help.

    all the best,

    Darren


Comments

  • Registered Users, Registered Users 2 Posts: 333 ✭✭s4dd


    i believe the getInteger() method in class Integer would sort ye. recognises the "0x" and prases the value after as a hex. hence why i'd suggest this over the valurOf() method.


    regards


  • Registered Users, Registered Users 2 Posts: 568 ✭✭✭phil


    If you're using parseInt(String str, int radix), then yes you're going to have trouble with the 0x at the start of the String. But remember, you're using Strings! Simply remove it by using the substring() method!

    This would have been the workaround you needed.
    Note: It's probably best to test that it exists at the start of the string, before blindly removing the first two characters.

    However, there is a purpose built function you can use, see Integer.decode().
    int dec_value = 0;
    String str = "0xA";
    
    try {
            dec_value = Integer.decode(str).intValue();
    }
    catch (NumberFormatException e)
    {
            e.printStackTrace();
    }
    
    System.out.println("Integer value = " + dec_value);
    


Advertisement