Converting a Hex String to an Int

I have a quick question. I am attempting to encode an Integer as a Hex String using Integer.toHexString(), which produces a max of eight hex characters.
I then need to convert this string back to an integer. I tried using Integer.parseInt(string, 16), but this only works for positive integers, because it expects a negative number to be designated with a "-" sign, which is the behavior of Integer.toString(int, 16).
I do not wish to represent the "-" sign in that manner, because I want to minimize the length of the hex string.
This method is time-critical, and I would like it to be as simple as possible, so I am looking for a solution in the standard libraries. Does anybody know of a method to convert the eight character hex representation which includes the sign bit as part of the eighth character back to an int using a method provided by the libraries?

int intVal = (int)Long.parseLong(str, 16);

Similar Messages

  • Converting a hex String to its corresponding hex value...?

    Yeah, I'm having quite a bit of fun guessing this one... :p
    I have a string of n characters and have used Integer.toHexString( ( int )str.charAt( i ) ) to convert each character to a string representing its hex value. Now I need to USE that value for bit-wise operations, like, say, applying the AND, OR, etc. operators...
    Example:
    hexvalue &= 0xC000FFFF; //the second value is the one extracted from the string;
    How can achieve this...? Any help is greatly appreciated... :}

    Since a Java char is numerically a Java short, you can apply bitwise operators to chars directly - the conversion to hex simply changes the way that the char is viewed; the result can also be viewed as a number in other bases.
    For instance, the char 'A' can be also be represented as any of the following values:
    binary - 1000001
    octal - 101
    decimal - 65
    hex - 41
    Likewise, 'Z' can also be viewed as
    binary - 1011010
    octal - 132
    decimal - 90
    hex - 5A
    "Anding" the letter 'A' with 'Z' ('A' & 'Z') or doing the same using any of the other representations will result in (binary 1000000, octal 100, decimal 64, or hex 40) - the bit pattern is the same, only the representation of the result varies.

  • Converting a byte array or hex string  into DES key

    i required to covert a hex represented of DES key into key object for cryptography operation to performed ...
    can you help me to find out how to convert a hex representaion of key int DES key object

    hi friend,
    I think the key size is more than the required size. For DES algorithm, the key size is 64 bit long.But the code u have given has more than 64 bit, because of which this exception has been raised.
    Reduce the key value to 64bit and try. If it doesnt work,try the code given below .I think it might be helpful for u
    import javax.crypto.*;
    import javax.crypto.spec.*;
    public class Cryption
         public byte[] encrypt(byte[] keyData,byte[] clearMessage)
              try
                   SecretKeySpec sks = new SecretKeySpec(keyData,"DES");
                   Cipher c = Cipher.getInstance ("DES");
                   c.init(Cipher.ENCRYPT_MODE,sks);
                   byte[] encryptedMessage = c.doFinal(clearMessage);
                   return encryptedMessage;
              catch(Exception e)
                   e.printStackTrace();
              return null;
         public byte[] decrypt(byte[] keyData,byte[] cipherMessage)
              try
                   SecretKeySpec sks = new SecretKeySpec(keyData,"DES");
                   Cipher c = Cipher.getInstance ("DES");
                   c.init(Cipher.DECRYPT_MODE,sks);
                   byte[] decryptedMessage = c.doFinal(cipherMessage);
                   return decryptedMessage;
              catch(Exception e)
                   e.printStackTrace();
              return null;
         public static void main(String[] args)
              String keyString = "ABCDEF12";
              byte keyValue[] = keyString.getBytes();
              Cryption encryption = new Cryption();
              String Message = "Hello Welcome to world of Cryptography";
              System.out.println("Key Value (represented in HEX form): "+keyString);
              System.out.println("Key Value (represented in byte array form): "+keyValue);
              System.out.println("Original Message : "+Message);
              byte[] encryptedMessage = encryption.encrypt(keyValue,Message.getBytes());
              System.out.println("Encrypted Message : "+new String(encryptedMessage));
              Cryption decryption = new Cryption();
              byte[] decryptedMessage = decryption.decrypt(keyValue,encryptedMessage);
              System.out.println("Decrypted Message : "+new String(decryptedMessage));
    output :
    Key Value (represented in HEX form): ABCDEF12
    Key Value (represented in byte array form): [B@43c749
    Original Message : Hello Welcome to world of Cryptography
    Encrypted Message : "O3�?�M�,����������,�]�3�����R�?>C$
    Decrypted Message : Hello Welcome to world of Cryptography
    whenever u use any algorithm, first findout the key size or range that algorithm supports. It is very important
    regards,
    Deepa Raghuraman

  • How could I choose some bytes from HEX string and then convert it to a decimal value?

    Hi I am working with an OMRON E5EN temperature controller using VISA serial to get data, I send the Read from Variable Area command and get this string  in hexa 0230 3130 3030 3030 3130 3130 3030 3030 3030 3030 3041 3203 71 or .01000001010000000000A2.q in ASCII this string means:
    02 STX
    3031 3030 Node and subadress
    3030 End Code Normal Completion
    3031 3031 Command Read from Variable Area
    3030 3030 respt code Normal completion
    3030 3030 3030 4132 Hexadecimal A2 = 162  (this is the temperature data that I want to show in decimal)
    03 ETX
    71 Block Check Character
    I want to choose the eight bytes for the temperature data and convert it to a decimal number. I have seen the examples to convert a Hexa string to decimal but I do not know how to choose the specifics bytes that I need.
    I have look for a driver but i didn´t find any. I am a beginner so please include especific topics for me to study in your answer.
    Thanks
    Carlos Fuentes Silva Queretaro Mexico 

    If the response always has the temperature starting with byte 15 and is always 8 bytes in length, you can use the String Subset function to get those bytes out of the string.  Then use Hex String to Number to convert to a decimal number.
    Well someone already beat me to the solution:
    Message Edited by tbob on 01-04-2008 04:42 PM
    - tbob
    Inventor of the WORM Global
    Attachments:
    HexStr2Decimal.png ‏7 KB

  • How to convert hex string to time stamp?

    Hello everyone..
    I am currently working on a project in which I have to read the data from a unit and display that data using LabVIEW. I am using serial communication for reading the data. The read data is in hex format. 
    Now, I want to convert this hex string to a time stamp value. I am reading total 16 bytes. How to convert this hex data to a time stamp value. I have developed a VI. But I want to know that the displayed time stamp is correct or not? Or suggest me some other solution. 
    I am using LabVIEW 2011.
    Thanks & Regards,
    Manisha
    Attachments:
    Test.vi ‏7 KB

    Hi mancan,
                      As Iam using LV2009 Iam unable to open your example.Anyway for converting hex to time stamp
    Thanks as kudos only

  • Which bytes should be edited in a WMF hex string stored in an RTF file in order to change image dimensions?

    I  would like to save the WMF file with proper dimensions as they are in the editor (my saved WMFs have the dimensions of my screen resolution).  They come from a RichEdit.
    Thanks.
    Edit:
    My goal is to convert the images that appear on a RichEdit to another format.
    Here is the fragment of the RTF:
    {\pict\wmetafile8\picw7407\pich9259\picwgoal4199\pichgoal5249 
    010009000003703e020000005a3e02000000050000000b0200000000050000000c022b24ef1c5a
    ffffffffffffff030000000000
    }\cf2\lang1033\b\f1\fs23\par
    For each 2 chars in this string I converted it to hex and saved it through a memory stream. Then I opened it in Paint or GIMP and there is the image.  I even can convert it to a PNG file through ImageMagick tool. But the dimensions are wrong. How to fix
    this?
    I am using Lazarus.
    I could guess that the header is not OK, but how they can be opened by Paint and converted? So I guess the dimensions info is wrong in the header. In GIMP even the dimensions are right, here a link to the GIMP's dialogbox confirmation with the dimensions
    it has encountered in the file (  http://s13.postimg.org/s536tgo9z/Metafile_in_GIMP.png  ).
    So the info is there, but is wrong. When I open the images in Paint, they are wrong. Microsoft Office Picture Manager can also open them correctly, but could not convert them so. I need to do it programmatically. TMetafile Delphi class could not open these
    files as well in order to be converted. So I could only edit the bytes.
    My RichEdit WMF data can not be accepted by ComputeAldusChecksum routine nor get a handle from SetWinMetaFileBits API call, which would convert it to an EMF format.
    procedure TMetafile.ReadWMFStream(Stream: TStream; Length: Longint);
    var
    WMF: TMetafileHeader;
    BitMem: Pointer;
    MFP: TMetaFilePict;
    begin
    NewImage;
    Stream.Read(WMF, SizeOf(WMF));
    if (WMF.Key <> WMFKEY) or (ComputeAldusChecksum(WMF) <> WMF.CheckSum) then
    raise EComponentError.Create('Invalid metafile.'); // <<<<<<<<<<<<<<< exception here
    Dec(Length, SizeOf(WMF));
    GetMem(Bitmem, Length);
    with FImage do
    try
    Stream.Read(BitMem^, Length);
    FImage.FInch := WMF.Inch;
    if WMF.Inch = 0 then
    WMF.Inch := 96;
    FWidth := MulDiv(WMF.Box.Right - WMF.Box.Left,25400,WMF.Inch);
    FHeight := MulDiv(WMF.Box.Bottom - WMF.Box.Top,25400,WMF.Inch);
    with MFP do
    begin
    MM := MM_ANISOTROPIC;
    xExt := 0;
    yExt := 0;
    hmf := 0;
    end;
    FHandle := SetWinMetaFileBits(Length, BitMem, 0, MFP); 
    if FHandle = 0 then
    raise EComponentError.Create('Invalid metafile.'); // <<<<<<<<<<<<<< exception here
    Enhanced := False;
    finally
    Freemem(BitMem, Length);
    end;
    end;

    Hi Antônio G,
    Based on your description, I’m afraid that it is not the correct forum for this issue, since this forum is to discuss:
    Visual Studio WPF/SL Designer, Visual Studio Guidance Automation Toolkit, Developer Documentation and Help System, and Visual Studio Editor.
    To make this issue clearly, would you mind letting us know more information about this issue? Which language are you using? Which kind of app are you developing?
    Reference:
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/a9e1857d-dd5b-443b-8633-397aea6e7b8c/help-on-properly-handling-wmf-mmanisotropic-image-in-rtf-file-when-extracted?forum=csharpgeneral
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/5b99d331-ef56-4d60-bf12-3e3b70783376/how-to-convert-a-hex-string-save-in-a-rtf-file-into-an-image-jpg-or-bmp?forum=csharpgeneral#a9219408-f73b-4e98-a9d8-7a1e0f20cdd9
    Maybe you could select the language development forum for this kind of issue. If not, please let me know more information about it, I will help you find a more appropriate forum.
    Best Regards,
    Jack
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How can I convert an ASCII string of variable length to a HEX number?

    Hello,
    I read data from the serial port 5 times in a second (while loop) and the number of bytes read varies every time.
    The data comes in as ASCII string, and I can see the HEX representation if I connect a HEX string indicator, but I need to permanently convert data to a HEX number. 
    How can that be done?

    Like This.
    Ton
    Free Code Capture Tool! Version 2.1.3 with comments, web-upload, back-save and snippets!
    Nederlandse LabVIEW user groep www.lvug.nl
    My LabVIEW Ideas
    LabVIEW, programming like it should be!

  • How can I convert a String into an int?

    I need to use command-line args. So I enter "java Main 123" and I want to use 123 not as a String but as an int.
    How can I convert it into an int?
    Thank You!!
    Sprocket

    Example method (you don't need to use a method unless you do this a lot)
    private int stringTOInt (String aString)
    int result = 0;
    try
    result = Integer.parseString(aString);
    catch (Exception ex)
    System.out.println ("Failed to convert string " + aString + " to int.");
    return result;
    }

  • Converting string to an int

    hi,
    is there anyway i can easily convert a string into a long int.
    I have an id string which consists of 11 characters, the first 3 are used to identify the type. the last 8 are numbers that need to go in a sequence.
    Eg, 44400000001, next would be 44400000002 and so on.
    i can break the string into two, but when i convert the last part into an int it does not keep the 0s. i need the length of this int to remain 8.
    thanks
    Shazan
    Edited by: shazan on Apr 24, 2008 11:27 AM

    shazan wrote:
    ...but when i convert the last part into an int it does not keep the 0s. i need the length of this int to remain 8.
    How do you mean, keep the zeros?
    int is short for integer, it doesn't have length as in number of characters...
    What about keeping the last part as String as well and converting it inside the calculations (or whatever you're doing)... or maybe convert it and do what you're doing and then convert it back to String with padded zeros?

  • Converting a String to an Int

    Hi,
    I am having trouble coding my programming. I need to compare two teams scores, and I believe to do this I have to convert the team name to an int. I am having problems with this.
    Any Help Please
    Thanks

    I'm going to assume that reading the information out of the file is already done so we'll press on with the rest of it.
    There's the cheap and easy solution
    1. Read the values from the row in the file into four variables
    String homeTeamName
    int homeTeamScore
    String visitingTeamName
    int visitingTeamScore
    if(homeTeamScore > visitingTeamScore){
        // Deal with the home team winning
    else if(homeTeamScore < visitingTeamScore){
        // Deal with the visiting team winning
    else{
        // Deal with a tie
    }No rocket science involved.
    Now, then there's a more tidy and graceful way to do it.
    The Team class holds information relevant to the team
    public class Team
        private String teamName ;
        private boolean homeTeam ;
        private int score ;
        // Don't forget accessors and mutators
    }The Game class holds among other things two instances of the Team class and a method to determine who won.
    public class Game
        private Team home ;
        private Team visitor ;
        // Probably lots of other stuff but here's the relevant part
        public Team getWinner() throws TieScoreException
            if(home.getScore() == visitor.getScore())
                throw new TieScoreException() ;
            else if(home.getScore() > visitor.getScore())
                return home ;
            else
                return visitor ;
    }Now obviously there would be a lot more to do but this gives you A framework in which to think. I likely wouldn't model it exactly this way but it's the first arrangement that my brain spat up and it gives you something to think about.
    Hope this helps,
    PS.

  • Need help to convert this format of string in a int value?

    public static int isNumber( String number, int defaultValue ) {
              int result;
              try {
                   result = Integer.parseInt(number);
              } catch( Exception e ) {
                   result = defaultValue;
              return result;
         }Hi, I have the above method that converts a string Number into a int value. It works fine if the string is a normal number 234 (without spaces) but I have a string in the following format:
    *(space)�23,000(space).*
    That is I have a "space" then a "Pound" sign then two numbers then a comma followed by three numbers and then a space again.
    Is there any way I can convert this format into a simple int value?
    Thanks for any guidance.
    Zub

    Hi, I tried the following code but it don't seem to work
         public static int isNumberTrimSpaces( String number, int defaultValue ) {
              number.trim();
              String parsed = "";
              for (int i = 0 ; i < number.length() && number.charAt(i) != ',' ; i++)
             if (Character.isDigit(number.charAt(i))) {
             parsed += number.charAt(i);}
              int result;
              try {
                   result = Integer.parseInt(number);
              } catch( Exception e ) {
                   result = defaultValue;
              return result;
         }Any Ideas? Also will the loop get rid of the pound sign?

  • How to convert String array into int.

    void getSoldSms(Vector vecSoldSms)
         String str[]=new String[vecSoldSms.size()];
         String words[]=new String[str.length]; // String array
              for(int i=0;i< vecSoldSms.size();i++)
                   str=(String)vecSoldSms.get(i);
              }               //End for
              for(int i=0;i<str.length;i++)
              words = str[i].split("\\|\\|");
              System.out.println();
              for(int j=0;j<1;j++)     
              int count[str.length]=Integer.parseInt(words[i]);
              System.out.print(count[j]*advance_count);
              } // end inner for loop
              }          //End for
         }          //End function getSoldSms
    how do i convert words which is a string array into int type. i kno string can be converted into int using interger.parseint. but wat abt string arrays??? plz help me out with the above code.

    i did tht its still giving the same errorFor Heaven's sake, what about taking a second to try to understand the code you're copying first? If you really can't fix the error yourself, you have a more serious problem than just convertingStrings to ints.
    And if you want { "1", "2", "3" } to be 123:
    StringBuffer b = new StringBuffer();
    for (int i = 0; i < array.length; i++) {
      b.append(array);
    int result = Integer.parseIn(b.toString());

  • Converting a string to several int.

    Hi I am having trouble getting a string to several integers. I have a String that looks like this: N163644. I need three integers with the numbers 16, 36 and 44 for further calculations. I have tried converting to char[] and then to int but it most be an easier way.
    thankful for all help.

    It works fine with this code.
    int degLat = Integer.parseInt(lat1.substring(1,3));
    Thanks..

  • Convert a byte/Byte - HEX STRING ?

    Hi ,
    My Problem is , I want to convert a byte/Byte value to hex string. If there is any way to convert bytes to hex strings then please tell me.
    please help me.

    Integer.toHexString(byteValue);
    http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Integer.html

  • Converting a String to an Int????  (Java)

    I am reading in a value from the user as a string. But I need to use that value as an int value. Can you parse a string to an int? Or can someone tell me another way I should be doing this?
    Thanks

    Integer.parseInt()
    Next time, search the forum, this gets asked every day.

Maybe you are looking for

  • How do i email a video clip from my iphone

    How do i email a 6 minute video clip from my iphone

  • Itunes on a mac

    I installed a theme on my emac as opposed to using shapeshifter. After restarting the computer i opened itunes and got a message telling me the application couldnt open because there was'nt enough memory available. This has never happen before. Okay

  • Replacing a inner join with for all entries

    Hi Team,    In a already developed program I am replacing a inner join with select query follow up with for-all-entris and passing the data to final internal table but in both the case the result should be same then only my replacement will be correc

  • EPM 11.1.2.1 CLUSTER COMPLETE

    Dear Gurus, I need to install second instance on wintel boxes (distribuited: 1-weblogic/ohs application box, 2-services, 3-essbase, 4- IIS- FDM) same as first instance. Products: HPCM, Planning, FDM, FR, WA I will need help on the following: 1) Does

  • Why is Safari not showing pages correctly ?

    Hi there ! I'm having a little Safari 5 trouble. Safari is not showing page layouts correctly, it seems it is not recognizing / reading css at all. Not one site shows correctly ! Whereas Firefox has no problem at all. On Safari, I had diverse small e