Int to hex?

Is there a predefined way to change an integer to hexidecimal?
For Instance:
int ip1 = 166;
ip1 to hex = 0xA6
I had thought I read about this in the docs, but can't find it.
Thanks

I appreciate the response. To explain my reasoning: I am building a byte array and I need to put each of the four number segments of an ip address into the array.
Would this work? Forgive the fast-coding.
String SrvrIP = srvrIpAddr.getHostAddress();  // i.e 166.10.10.0
StringTokenizer ip = new StringTokenizer( SrvrIP, "." );
int ip1 = Integer.parseInt(ip.nextToken());
int ip2 = Integer.parseInt(ip.nextToken());
int ip3 = Integer.parseInt(ip.nextToken());
int ip4 = Integer.parseInt(ip.nextToken());
byte[] buf = new byte[512];                // Does it give me this??
buf[0] = Integer.toHexString(ip1);              // buf[0] = 0xA6
buf[1] = Integer.toHexString(ip1);              // buf[1] = 0x0A
buf[2] = Integer.toHexString(ip1);              // buf[2] = 0x0A
buf[3] = Integer.toHexString(ip1);              // buf[3] = 0x00Thanks

Similar Messages

  • Int to Hex Progam

    Could someone help resolve this problem : I have created a program to change int to hex but it does not seem to woek ? What could be wrong ?
    import java.lang.String;
    import javax.swing.JOptionPane; // import class JOptionPane
    public class KcHexConverter {
    public static void main( String args[] )
         String value, s;// first string entered by user
         int ni=0;
              // read in first number from user as a string
              value = JOptionPane.showInputDialog( "Enter integer" );
    // convert numbers from type String to type Hex
              ni = Integer.parseInt(value, 16);
              s = Integer.toHexString(ni);
    // display the results
    JOptionPane.showMessageDialog(null, "The equvalent in Hexadecimal is: " +s, "Results", JOptionPane.PLAIN_MESSAGE );
    System.exit( 0 ); // terminate the program
    }

    Hi
    you need to change:
    ni = Integer.parseInt(value);//no need for a radix it is base 10
    and you should catch a possible NumberFormatException (sb enters a letter).

  • USB Output Buffers - int to Hexed Chars

    Hi all
    With regards sending data to a USB device I set up a char like so:
    size_t bufferSize = 8;
    char *buffer = malloc(bufferSize);
    I can then populate my bytes in hex (which seems to be the normal way of doing it).
        buffer[0] = 0xFF;
        buffer[1] = 0xEA;
    The two fold question is will I have any issues if i populate the char buffers with integers?
        int value = 256;
        buffer[0] = value;
    or does it have to be in hex?
    If it requires hex (or even if not cos it would be good to know). What the best way to convert and integer to a hexed char?
    Cheers
    Steve

    It doesn't matter if you specify the value in hexadecimal, decimal, octal or binary (or any other numbering system for that matter).
    A number has the same value no matter what base you use.

  • Converting Hex to Integer Value

    I'm trying to convert hex code to the corresponding integer, which can then be used to display a character.
    For example I have the code.
    int i = 0xE7;
    System.out.println(i);
    System.out.write(i)This produces the output as expected with the first output outputting 231, and the second line outputting the corresponding character.
    My problem comes when trying to make it so the hex code is variable.
    For example, I receive an output of 7
    This output is then the last digit of the hex code (so i check if needs to be converted to a, b etc.) then try and combine it with the prefix 0xE to create the hex code.
    I'm not quite sure how to do this bit as I cant carry out
    num = 7;
    hex = "0xE"+num;
    int i = hex;as the last line doesn't calculate due to hex being a string.
    Many thanks for your help.

    leesto wrote:
    The char array is currently being created using:
    char [] hexchar = "0123456789ABCDEF".toCharArray();
    Look this is OK, you need to do nothing but just the following:
    // I am using the very first example you provided
    // i is the index for the char
    String hex = "0E" + hexchar;
    Integer.parseInt(hex, 16);
    System.out.println(i);

  • Java on Linux vs. Windows

    Dear All,
    I was able to write below AES/CFB/NoPadding encryption/decryption program (with many thanks to the Internet) and it works fine on Windows. But it's "getByte()" gives problems on Linux.
    Which is the "symmKey.length()" inside "SymmCipher" constructor is only 15 chars. But "symmKey.getBytes().length" has become 33.
    Can anybody answer?
    Thanks in advanced.
    - amilww
    // aesDemo.java
    class aesDemo
         public static void main(String[] args) throws Exception
              String keyHexStr = "CAABBCCDDEE11223344556677889900F";
              String ivStr     = "0000000000000001";
              String inputStr  = "This in a test message";
              // Intermediate variables
              String cipherTextStr, plainTextStr,
                     reqHexMsgStr,  repHexMsgStr,
                     repMsgStr;
              SymmCipher symmCipher = new SymmCipher("AES/CFB/NoPadding",
                                                     new String(Util.hex2Bytes(keyHexStr)),
                                                     ivStr);
              // Encrypt the input string
              cipherTextStr = symmCipher.encrypt(inputStr);
              // Convert to an uppercase Hex request string
              reqHexMsgStr = Util.bytes2Hex(cipherTextStr.getBytes()).toUpperCase();
              // Obtain the reply; assume to be the request
              repHexMsgStr = reqHexMsgStr;
              // Convert reply hex message to a string
              repMsgStr = new String(Util.hex2Bytes(repHexMsgStr));
              // Decrypt the reply string
              plainTextStr = symmCipher.decrypt(repMsgStr);
              // Debub output
              System.out.println("=============================================");
              System.out.println("Encrypting/decrypting using AES/CFB/NoPadding");
              System.out.println("---------------------------------------------");
              System.out.println("Input String: '" + inputStr + "'");
              System.out.println("Encr request: '" + cipherTextStr + "'");
              System.out.println("Req Hex Msg:  '" + reqHexMsgStr + "'");
              System.out.println("Rep Hex Msg:  '" + repHexMsgStr + "'");
              System.out.println("Encr reply:   '" + repMsgStr + "'");
              System.out.println("Response:     '" + plainTextStr + "'");
              System.out.println("=============================================");
    // SymmCipher.java
    import javax.crypto.Cipher;
    import javax.crypto.spec.IvParameterSpec;
    import javax.crypto.spec.SecretKeySpec;
    class SymmCipher
         private String cipherForm;
         // e.g.: "AES/CFB/NoPadding", "DES/CTR/NoPadding", "DES/ECB/PKCS5Padding"
         private String cipherMethod;
         private SecretKeySpec   keySpec;
         private IvParameterSpec ivSpec;
         private Cipher          cipher;
         public SymmCipher(String cipherForm, String symmKey, String iv) throws Exception
              this.cipherForm   = cipherForm;
              this.cipherMethod = this.cipherForm.split("/")[0];
              this.keySpec = new SecretKeySpec(symmKey.getBytes(), this.cipherMethod);
              this.ivSpec  = new IvParameterSpec(iv.getBytes());
              this.cipher = Cipher.getInstance(this.cipherForm);
         public String encrypt(String plainText) throws Exception
              // Encrypting...
              this.cipher.init(Cipher.ENCRYPT_MODE, this.keySpec, this.ivSpec);
              return new String(this.cipher.doFinal(plainText.getBytes()));
         public String decrypt(String cipherText) throws Exception
              // Decrypting...
              this.cipher.init(Cipher.DECRYPT_MODE, this.keySpec, this.ivSpec);
              return new String(this.cipher.doFinal(cipherText.getBytes()));
    // Util.java
    class Util
         public static String bytes2Hex(byte buf[])
              StringBuffer strbuf = new StringBuffer(2 * buf.length);
              for (int i = 0; i < buf.length; i++)
                   if (((int) buf[i] & 0xff) < 0x10)
                        strbuf.append("0");
                   strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
              return strbuf.toString();
         public static byte[] hex2Bytes(String hex)
              int    len = hex.length();
              byte[] buf = new byte[((len + 1) / 2)];
              int i = 0, j = 0;
              if (1 == (len % 2))
                   buf[j++] = (byte) hexDigit(hex.charAt(i++));
              while (i < len)
                   buf[j++] = (byte) ((hexDigit(hex.charAt(i++)) << 4) |
                   hexDigit(hex.charAt(i++)));
              return buf;
          * Returns the number from 0 to 15 corresponding to the hex digit <i>ch</i>.
          * @param ch hex digit character (must be 0-9A-Fa-f)
          * @return   numeric equivalent of hex digit (0-15)
         public static int hexDigit(char ch)
              if (('0' <= ch) && ('9' >= ch))
                   return ch - '0';
              if (('A' <= ch) && ('F' >= ch))
                   return ch - 'A' + 10;
              if (('a' <= ch) && ('f' >= ch))
                   return ch - 'a' + 10;
              return(0);     // any other char is treated as 0
    }

    This statement
         return new String(this.cipher.doFinal(plainText.getBytes()));     has two problems.
    1) It relies on the default character encoding when converting the plainText to bytes and the default character encoding is platform, operating system and user dependent. It is far far better to specify an encoding yourself - I always use utf-8.
    2) You are converting the essentially random binary result of the encryption to a String using new String(encrypted bytes). String should never be used as a container for binary data unless something like Hex or Base64 is used because, depending on the character encoding, it is not reversible for most character encoding. If you need a Hex or Base64 encoder then Google for Jakarta Commons Codec.

  • How to decrypt AES using a key

    The example here will Generate the secret key specs first.
    http://java.sun.com/developer/technicalArticles/Security/AES/AES_v1.html
    I already have a Decrypt Key used in my server application. How can I use that key to decrypt the msg sent from server?

    Hi
    I wrote this code to check Java encryption with AES and a key. This worked fine for me. Please have a look.
    Encrypt and decrypt using the DES private key algorithm
    import java.security.*;
    import javax.crypto.*;
    import javax.crypto.spec.SecretKeySpec;
    import org.bouncycastle.jce.provider.BouncyCastleProvider;
    public class AESEncrypt {
        public static void main (String[] args) throws Exception {
            Security.addProvider(new BouncyCastleProvider());
            byte[] plainText = "LOGIN=2222=v2-0-b7=SMST=smst=ASI".getBytes("utf-8");
            // Get a DES private key
            System.out.println( "\nAES key" );
            String strKey = "75de8a33d3f18f1c29d86fa42b1894c7";
            byte[] keyBytes = hexToBytes(strKey);
            // skeyspec is the key to encrypt and decrypt
            SecretKeySpec skeySpec = new SecretKeySpec(keyBytes, "AES");
            System.out.println("Key: " + asHex(key.getEncoded()));
            System.out.println( "Finish generating AES key" );
            // Creates the DES Cipher object (specifying the algorithm, mode, and padding).
            Cipher cipher = Cipher.getInstance("AES/ECB/PKCS7Padding");
            // Print the provider information
            System.out.println( "\n" + cipher.getProvider().getInfo() );
            System.out.println( "\nStart encryption" );
            // Initializes the Cipher object.
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            // Encrypt the plaintext using the public key
            byte[] cipherText = cipher.doFinal(plainText);
            System.out.println( "Finish encryption: cipherText: " + asHex(cipherText));
            System.out.println( "\nStart decryption" );
            // Initializes the Cipher object.
            cipher.init(Cipher.DECRYPT_MODE, skeySpec);
            // Decrypt the ciphertext using the same key
            byte[] newPlainText = cipher.doFinal(cipherText);
            System.out.println( "Finish decryption: " );
            System.out.print( asHex(newPlainText) );
        public static String asHex (byte buf[]) {
          StringBuffer strbuf = new StringBuffer(buf.length * 2);
          int i;
          for (i = 0; i < buf.length; i++) {
           if (((int) buf[i] & 0xff) < 0x10)
             strbuf.append("0");
           strbuf.append(Long.toString((int) buf[i] & 0xff, 16));
          return strbuf.toString();
        public static byte[] hexToBytes(char[] hex) {
            int length = hex.length / 2;
            byte[] raw = new byte[length];
            for (int i = 0; i < length; i++) {
                int high = Character.digit(hex[i * 2], 16);
                int low = Character.digit(hex[i * 2 + 1], 16);
                int value = (high << 4) | low;
                if (value > 127) value -= 256;
                raw[i] = (byte)value;
            return raw;
        public static byte[] hexToBytes(String hex) {
            return hexToBytes(hex.toCharArray());
    }

  • Problem with a method

    I have a problem with the getRGB(int x, int y) method of the BufferedImage class :
    I've load an image in it :
    1:// b is my bufferedimage clas and myimage is an image
    2:b.getGraphics().drawImage(myimage, 0, 0, this);
    3:// g is the graphics object of my paint method
    4:g.drawImage(b, 634, 225, null);
    5:// This write -16777216 and 10, 10 is a black point
    6:System.out.println(b.getRGB(10, 10));
    I think the problem is at the second line. But i'm not sure. Can somebody help ?

    That's probably not what you meant. You can do a binary and:int r = (hex & 0x00FF0000) >> 16;
    int g = (hex & 0x0000FF00) >> 8;
    int b = (hex & 0x000000FF);

  • Store bufferimage in array

    Hello friends.
    I want scan an image (png) and store all the pixel values in array. My image has only three colors (white,red & blue)
    basically its a graph with blue for co-ordinate
    white as background
    and the red color is the plotted area of graph.
    I am writing the folowing code
    try{
    img = ImageIO.read(new File("img/image0.png"));
    } catch (IOException e) { }
    w= img.getWidth(this);
    h=img.getHeight(this);
    int[] rgbs = new int[w*h];
    BufferedImage bimage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
    for(int i =0;i<(h-1);i++)
    { for (int j = 0;j<(w-1);j++)
    {      rgbs[i] = (bimage.getRGB(i,j));
    System.out.println(rgbs);}}
    MY aim is to store either int or hex values of all the pixels in the array.
    So tht when i scan the array, i can get the location at which red color is stored in the array.
    Plz help my friends.....

    It's easier to just change the code than explain everything, but I will make some points:
    The random number function only runs once, so all the numbers inside the loop will be the same.
    The key to what you wanted is the shift register, which allows keeping the same array between different iterations.
    A for loop is only relvant if you know in advance how many times you are going to run, not if you are waiting for user input.
    If you are using a for loop and you don't need to see the array inside the loop, you can simply wire the numeric value out of the loop and it will be built into a 1D array automatically.
    To learn more about LabVIEW, I suggest you try searching this site and google for LabVIEW tutorials. Here, here, here, here and here are a few you can start with and here are some tutorial videos. You can also contact your local NI office and join one of their courses.
    In addition, I suggest you read the LabVIEW style guide and the LabVIEW user manual (Help>>Search the LabVIEW Bookshelf).
    Try to take over the world!
    Attachments:
    ArrayExample mod.vi ‏19 KB

  • Why doesn't my while loop end?

    * Main method
    public static void main(String args[])
    Scanner sc = new Scanner(System.in);
    //get input
    String hexa = "nothing";
    while (hexa != "q")
    System.out.println("");
    System.out.println("Please enter a hexadecimal to convert to binary, enter q to quit");
    hexa = sc.next();
    int hexlength = hexa.length();
    for (int i = 0; i < hexlength; i ++)
    char hexadec = hexa.charAt(i);
    //send to subprogram
    findBinary(hexadec, hexlength);
    why doesn't my while loop end when i enter q?

    The equals method returns a boolean (true/false). So you simply negate the returned value.
    if( ! methodCall()) {
    }

  • Parsing machine code

    I have a need for a program that can parse a 4-digit hexadecimal code and take action on it. The first and last digits are frequently the most important, but all of the digits can be varied. I have several methods in mind, but what is the fastest or most efficient way in java to operate on the digits individually?

    You could do something similar to this.
    public class HexToInt {
         public static void main(String args[]){
              String hex = "A7FE"; //Hexadecimal number
              int count = hex.length();
              String[] c = new String[count];
              for(int i = 0; i < count; i++){
                   c[i] = String.valueOf(hex.charAt(i)); //Grab single hex character
                   System.out.println("Hex digit at element " + i + " is " + convert(c)); //Convert character to integer
         public static int convert(String hex){
              return Integer.valueOf(hex, 16);
    }I'm not exactly sure if this was the kind of action you were looking for, but this is just a simple program that converts a single hexadecimal character from a string and prints it out as an integer.                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

  • Wireless errors on WLC

     hi
    Ikeep getting this error on the WLC where users kept getting kicked off the the wireless network
    %DOT1X-3-INVALID_WPA_KEY_MSG_STATE: 1x_eapkey.c:848 Received EAPOL-key M2 msg has invalid information when mobile is
    in START  state - invalid secure bit; KeyLen 24, Key type 1, client a4:4e:31:20:32:fc
    is this a Client issue or Controller issue

    Error Message    %DOT1X-3-INVALID_WPA_KEY_MSG_STATE: Received invalid [chars] msg in
    [chars] state - [chars]; len [int], key type [int], client
    [hex]:[hex]:[hex]:[hex]:[hex]:[hex]
    Explanation    Client authentication failed because of an authentication protocol error between the client and access point.
    Recommended Action    If the problem persists, try upgrading the client driver software or using different client software to isolate the cause. Also investigate possible intruder activity.

  • 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);

  • Hex to Int

    Hey guys, can someone help me out here ..... i need to convert hex to int. I'm relatively new to java. Kindly bail me out here

    Check out the Integer static method with the signature:
    public static int parseInt(String s, int radix) throws NumberFormatException
    You should note that "int" is a primitive java type for (nonfactional)
    numbers, and "hex" is (presumably) a String. That is they are very
    different sorts of thing. The "radix" in the method referred to above
    is 16 in the case of hex strings.
    There is also a static decode(String) method.
    You can read about both here: http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Integer.html

  • String to Int and Int to String

    How can I convert a string to Int & and an Int to String ?
    Say I've
    String abc="234"
    and I want the "int" value of "abc", how do I do it ?
    Pl. help.

    String.valueOf(int) takes an int and returns a string.
    Integer.parseInt(str) takes a string, returns an int.
    For all the others long, double, hex etc. RTFM :)

  • How to convert hex into a string value

    hei evryone!
    can anyone please help me on how to convert a hex value into a string suppose.. Example i want to convert 4275646479 which is a hex value, into a string "BUDDY"? how will i do that???
    Any suggestion, tutorial site would be appreciated?
    Thx!

    something like this will convert string to byte[]
    e.g.
    you want to convert following.
    656667 => ABC
    String toConvert = "656667";
    byte[] returnVal = String2byteArr (toConvert );
    String FinalStr = new String(returnVal);
    public static byte[] String2byteArr(String Result)
    byte[] byteRet = new byte[Result.length()/2];
    int k=0;
    for (int j=0; j<(Result.length()); j+=2)
    try
    Integer I = new Integer (0);
    I = I.decode ("0x"+Result.substring(j, j+2));
    int i = I.intValue ();
    if (i > 127)
    i = i - 256;
    byteRet[k++] = new Integer(i).byteValue();
    catch(Exception e)
    System.err.println(e);
    return byteRet;
    }// String2byteArr
    Hope this will help you, So that i can get 3$ (:-)
    Avi

Maybe you are looking for

  • Transferring services and double billing...has it happened to you?

    I moved back in September of 2013. My goal was to keep all of my Verizon services (FIOS, Phone, Internet &Wireless) and continue to remain a happy Verizon customer, I am still a customer but not that happy, Prior to our move we had been a one bill cu

  • Satellite C660-108 does not boot if USB Bluetooth dongle connected

    Hiya, I hope you would help me. I am having an issue with my bluetooth dongle and satellite c660-108. It works all perfectly. It connects devices via bluetooth and I can do everything I want. But then when I am shutting down laptop and turning on aga

  • How to add special characters to field?

    As per topic... Virtual Office | Servcorp http://www.servcorp.com.au/ http://www.servcorp.net/

  • Backup requires 1099GB , but only 300GB available !

    I have at least figured out part of this problem. First I get the message: "Are you sure you want to back up on the disk your original data is on." But I am choosing the first partition of Bay 2 HD which is a 1TB partitioned into 2 500GB's. I have a

  • Mac network performance issue

    I've just had a new ISP hookup. My WiFi is blazing fast. But my Mac network speed is slowwwww. Speedtest.net just reported: Ping: 253ms Download: 1.12Mbps Upload: 0.43 Mbps On my iPad via Wifi, I get: Ping: 19ms Download: 13.88Mbps Upload: 0.90Mbps M