2 Replies Latest reply: Nov 4, 2012 2:42 AM by sabre150 RSS

    String Hex array to Byte array

      Hello -

      In my class i have the following as a private variable -

      private static byte[] keyValue = new byte[] {(byte)0xAB, (byte)0x3C, (byte)0x32, (byte)0xAB, (byte)0x5D};

      But, i want to just declare the variable in the class and instantiate it in a method.

      for example

      private static method1(String arg){
      keyValue = arg;

      arg is in the form of "new byte[] {(byte)0xAB, (byte)0x3C, (byte)0x32, (byte)0xAB, (byte)0x5D}"

      How can i achive the same results?

      Thank you for your time and thoughts...
        • 1. Re: String Hex array to Byte array
          arg is in the form of "new byte[] {(byte)0xAB, (byte)0x3C, (byte)0x32, (byte)0xAB, (byte)0x5D}"
          How? Why? Why not remove the quotes and change the argument type to byte[]? And eliminate the whole problem?
          • 2. Re: String Hex array to Byte array
            While I agree with EJP I can envisage a situation where the data might be presented in this form. Given this, to my mind the simplest approach is then to use a regular expression of say "0x([0-9A-F]{2})" with the Matcher.find() method to iterate though the argument string looking for matches then convert each 2 hex digit String to a byte before writing to an array. A two pass approach can be used where the first pass is used to find the length of the array.

            If you are not happy with using regular expressions then you could write a simple parser using just the methods of String.

            Note - in the regex one can allow the hex digits and the 'x' to be upper or lower case by just making the regex case insensitive.