How do I initialize a byte array in Java?





.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty{ height:90px;width:728px;box-sizing:border-box;
}







117















I have to store some constant values (UUIDs) in byte array form in java, and I'm wondering what the best way to initialize those static arrays would be. This is how I'm currently doing it, but I feel like there must be a better way.



private static final byte CDRIVES = new byte { (byte)0xe0, 0x4f, (byte)0xd0,
0x20, (byte)0xea, 0x3a, 0x69, 0x10, (byte)0xa2, (byte)0xd8, 0x08, 0x00, 0x2b,
0x30, 0x30, (byte)0x9d };
private static final byte CMYDOCS = new byte { (byte)0xba, (byte)0x8a, 0x0d,
0x45, 0x25, (byte)0xad, (byte)0xd0, 0x11, (byte)0x98, (byte)0xa8, 0x08, 0x00,
0x36, 0x1b, 0x11, 0x03 };
private static final byte IEFRAME = new byte { (byte)0x80, 0x53, 0x1c,
(byte)0x87, (byte)0xa0, 0x42, 0x69, 0x10, (byte)0xa2, (byte)0xea, 0x08,
0x00, 0x2b, 0x30, 0x30, (byte)0x9d };
...
and so on


Is there anything I could use that may be less efficient, but would look cleaner?
for example:



private static final byte CDRIVES =
new byte { "0xe04fd020ea3a6910a2d808002b30309d" };









share|improve this question





























    117















    I have to store some constant values (UUIDs) in byte array form in java, and I'm wondering what the best way to initialize those static arrays would be. This is how I'm currently doing it, but I feel like there must be a better way.



    private static final byte CDRIVES = new byte { (byte)0xe0, 0x4f, (byte)0xd0,
    0x20, (byte)0xea, 0x3a, 0x69, 0x10, (byte)0xa2, (byte)0xd8, 0x08, 0x00, 0x2b,
    0x30, 0x30, (byte)0x9d };
    private static final byte CMYDOCS = new byte { (byte)0xba, (byte)0x8a, 0x0d,
    0x45, 0x25, (byte)0xad, (byte)0xd0, 0x11, (byte)0x98, (byte)0xa8, 0x08, 0x00,
    0x36, 0x1b, 0x11, 0x03 };
    private static final byte IEFRAME = new byte { (byte)0x80, 0x53, 0x1c,
    (byte)0x87, (byte)0xa0, 0x42, 0x69, 0x10, (byte)0xa2, (byte)0xea, 0x08,
    0x00, 0x2b, 0x30, 0x30, (byte)0x9d };
    ...
    and so on


    Is there anything I could use that may be less efficient, but would look cleaner?
    for example:



    private static final byte CDRIVES =
    new byte { "0xe04fd020ea3a6910a2d808002b30309d" };









    share|improve this question

























      117












      117








      117


      27






      I have to store some constant values (UUIDs) in byte array form in java, and I'm wondering what the best way to initialize those static arrays would be. This is how I'm currently doing it, but I feel like there must be a better way.



      private static final byte CDRIVES = new byte { (byte)0xe0, 0x4f, (byte)0xd0,
      0x20, (byte)0xea, 0x3a, 0x69, 0x10, (byte)0xa2, (byte)0xd8, 0x08, 0x00, 0x2b,
      0x30, 0x30, (byte)0x9d };
      private static final byte CMYDOCS = new byte { (byte)0xba, (byte)0x8a, 0x0d,
      0x45, 0x25, (byte)0xad, (byte)0xd0, 0x11, (byte)0x98, (byte)0xa8, 0x08, 0x00,
      0x36, 0x1b, 0x11, 0x03 };
      private static final byte IEFRAME = new byte { (byte)0x80, 0x53, 0x1c,
      (byte)0x87, (byte)0xa0, 0x42, 0x69, 0x10, (byte)0xa2, (byte)0xea, 0x08,
      0x00, 0x2b, 0x30, 0x30, (byte)0x9d };
      ...
      and so on


      Is there anything I could use that may be less efficient, but would look cleaner?
      for example:



      private static final byte CDRIVES =
      new byte { "0xe04fd020ea3a6910a2d808002b30309d" };









      share|improve this question














      I have to store some constant values (UUIDs) in byte array form in java, and I'm wondering what the best way to initialize those static arrays would be. This is how I'm currently doing it, but I feel like there must be a better way.



      private static final byte CDRIVES = new byte { (byte)0xe0, 0x4f, (byte)0xd0,
      0x20, (byte)0xea, 0x3a, 0x69, 0x10, (byte)0xa2, (byte)0xd8, 0x08, 0x00, 0x2b,
      0x30, 0x30, (byte)0x9d };
      private static final byte CMYDOCS = new byte { (byte)0xba, (byte)0x8a, 0x0d,
      0x45, 0x25, (byte)0xad, (byte)0xd0, 0x11, (byte)0x98, (byte)0xa8, 0x08, 0x00,
      0x36, 0x1b, 0x11, 0x03 };
      private static final byte IEFRAME = new byte { (byte)0x80, 0x53, 0x1c,
      (byte)0x87, (byte)0xa0, 0x42, 0x69, 0x10, (byte)0xa2, (byte)0xea, 0x08,
      0x00, 0x2b, 0x30, 0x30, (byte)0x9d };
      ...
      and so on


      Is there anything I could use that may be less efficient, but would look cleaner?
      for example:



      private static final byte CDRIVES =
      new byte { "0xe04fd020ea3a6910a2d808002b30309d" };






      java arrays byte






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Jun 26 '12 at 13:33









      dficklingdfickling

      1,15521012




      1,15521012
























          9 Answers
          9






          active

          oldest

          votes


















          101














          Using a function converting an hexa string to byte, you could do



          byte CDRIVES = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");


          I'd suggest you use the function defined by Dave L in Convert a string representation of a hex dump to a byte array using Java?



          I insert it here for maximum readability :



          public static byte hexStringToByteArray(String s) {
          int len = s.length();
          byte data = new byte[len / 2];
          for (int i = 0; i < len; i += 2) {
          data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
          + Character.digit(s.charAt(i+1), 16));
          }
          return data;
          }


          If you let CDRIVES static and final, the performance drop is irrelevant.






          share|improve this answer

































            59














            byte myvar = "Any String you want".getBytes();


            String literals can be escaped to provide any character:



            byte CDRIVES = "u00e0u004fu00d0u0020u00eau003au0069u0010u00a2u00d8u0008u0000u002bu0030u0030u009d".getBytes();





            share|improve this answer





















            • 46





              Doesn't that turn the string "0000" to {0x30,0x30,0x30,0x30} (ASCII) rather than {0x00,0x00,0x00,0x00} (binary) as desired by the poster?

              – jww
              Aug 31 '14 at 15:57






            • 7





              You're not answering the right question.

              – Sotirios Delimanolis
              May 16 '16 at 18:01






            • 1





              And this garnered 52 upvotes?! Oi vey.

              – Lawrence Dol
              Jul 14 '16 at 2:30








            • 2





              This is plain wrong.

              – rjha94
              Nov 9 '16 at 16:59






            • 5





              Look at the question's title. Then look back at this answer. Now tell me, what's wrong about it? It might not solve the poster's particular issue, but it sure solved mine. I needed to transform a string into a byte array to use as a seed for a pseudorandom number generator and this worked like a charm.

              – e18r
              Sep 14 '18 at 15:55



















            30














            In Java 6, there is a method doing exactly what you want:



            private static final byte CDRIVES = javax.xml.bind.DatatypeConverter.parseHexBinary("e04fd020ea3a6910a2d808002b30309d")


            Alternatively you could use Google Guava:



            import com.google.common.io.BaseEncoding;
            private static final byte CDRIVES = BaseEncoding.base16().lowerCase().decode("E04FD020ea3a6910a2d808002b30309d".toLowerCase());


            The Guava method is overkill, when you are using small arrays. But Guava has also versions that can parse input streams. This is a nice feature when dealing with big hexadecimal inputs.






            share|improve this answer


























            • The Guava example doesn't quite work as written - it needs to be base16().lowerCase().decode(...) if you have lower case hex digits. docs.guava-libraries.googlecode.com/git/javadoc/com/google/…

              – Peter DeGlopper
              Sep 1 '15 at 21:43











            • @PeterDeGlopper Good finding, I've updated the answer so the code now handles strings with both lower and upper case characters.

              – stefan.schwetschke
              Sep 2 '15 at 7:06











            • javax.xml.bind was sadly removed in Java 9.

              – randomdude999
              Jan 5 at 22:02



















            7














            You can use the Java UUID class to store these values, instead of byte arrays:



            UUID

            public UUID(long mostSigBits,
            long leastSigBits)


            Constructs a new UUID using the specified data. mostSigBits is used for the most significant 64 bits of the UUID and leastSigBits becomes the least significant 64 bits of the UUID.






            share|improve this answer































              2














              As far as a clean process is concerned you can use ByteArrayOutputStream object...



              ByteArrayOutputStream bObj = new ByteArrayOutputStream();
              bObj.reset();


              //write all the values to bObj one by one using



              bObj.write(byte value)


              // when done you can get the byte using



              CDRIVES = bObj.toByteArray();


              //than you can repeat the similar process for CMYDOCS and IEFRAME as well,



              NOTE This is not an efficient solution if you really have small array.






              share|improve this answer

































                1














                My preferred option in this circumstance is to use org.apache.commons.codec.binary.Hex which has useful APIs for converting between Stringy hex and binary. For example:




                1. Hex.decodeHex(char data) which throws a DecoderException if there are non-hex characters in the array, or if there are an odd number of characters.


                2. Hex.encodeHex(byte data) is the counterpart to the decode method above, and spits out the char.


                3. Hex.encodeHexString(byte data) which converts back from a byte array to a String.



                Usage: Hex.decodeHex("dd645a2564cbe648c8336d2be5eafaa6".toCharArray())






                share|improve this answer

































                  1














                  A solution with no libraries, dynamic length returned, unsigned integer interpretation (not two's complement)



                      public static byte numToBytes(int num){
                  if(num == 0){
                  return new byte{};
                  }else if(num < 256){
                  return new byte{ (byte)(num) };
                  }else if(num < 65536){
                  return new byte{ (byte)(num >>> 8),(byte)num };
                  }else if(num < 16777216){
                  return new byte{ (byte)(num >>> 16),(byte)(num >>> 8),(byte)num };
                  }else{ // up to 2,147,483,647
                  return new byte{ (byte)(num >>> 24),(byte)(num >>> 16),(byte)(num >>> 8),(byte)num };
                  }
                  }





                  share|improve this answer































                    0














                    You can use this utility function:



                    public static byte fromHexString(String src) {
                    byte biBytes = new BigInteger("10" + src.replaceAll("\s", ""), 16).toByteArray();
                    return Arrays.copyOfRange(biBytes, 1, biBytes.length);
                    }


                    Unlike variants of Denys Séguret and stefan.schwetschke, it allows inserting separator symbols (spaces, tabs, etc.) into the input string, making it more readable.



                    Example of usage:



                    private static final byte CDRIVES
                    = fromHexString("e0 4f d0 20 ea 3a 69 10 a2 d8 08 00 2b 30 30 9d");
                    private static final byte CMYDOCS
                    = fromHexString("BA8A0D4525ADD01198A80800361B1103");
                    private static final byte IEFRAME
                    = fromHexString("80531c87 a0426910 a2ea0800 2b30309d");





                    share|improve this answer































                      -2














                      private static final int CDRIVES = new int {0xe0, 0xf4, ...};


                      and after access convert to byte.






                      share|improve this answer






















                        protected by Nilesh Rathod May 5 '18 at 10:35



                        Thank you for your interest in this question.
                        Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                        Would you like to answer one of these unanswered questions instead?














                        9 Answers
                        9






                        active

                        oldest

                        votes








                        9 Answers
                        9






                        active

                        oldest

                        votes









                        active

                        oldest

                        votes






                        active

                        oldest

                        votes









                        101














                        Using a function converting an hexa string to byte, you could do



                        byte CDRIVES = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");


                        I'd suggest you use the function defined by Dave L in Convert a string representation of a hex dump to a byte array using Java?



                        I insert it here for maximum readability :



                        public static byte hexStringToByteArray(String s) {
                        int len = s.length();
                        byte data = new byte[len / 2];
                        for (int i = 0; i < len; i += 2) {
                        data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                        + Character.digit(s.charAt(i+1), 16));
                        }
                        return data;
                        }


                        If you let CDRIVES static and final, the performance drop is irrelevant.






                        share|improve this answer






























                          101














                          Using a function converting an hexa string to byte, you could do



                          byte CDRIVES = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");


                          I'd suggest you use the function defined by Dave L in Convert a string representation of a hex dump to a byte array using Java?



                          I insert it here for maximum readability :



                          public static byte hexStringToByteArray(String s) {
                          int len = s.length();
                          byte data = new byte[len / 2];
                          for (int i = 0; i < len; i += 2) {
                          data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                          + Character.digit(s.charAt(i+1), 16));
                          }
                          return data;
                          }


                          If you let CDRIVES static and final, the performance drop is irrelevant.






                          share|improve this answer




























                            101












                            101








                            101







                            Using a function converting an hexa string to byte, you could do



                            byte CDRIVES = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");


                            I'd suggest you use the function defined by Dave L in Convert a string representation of a hex dump to a byte array using Java?



                            I insert it here for maximum readability :



                            public static byte hexStringToByteArray(String s) {
                            int len = s.length();
                            byte data = new byte[len / 2];
                            for (int i = 0; i < len; i += 2) {
                            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                            + Character.digit(s.charAt(i+1), 16));
                            }
                            return data;
                            }


                            If you let CDRIVES static and final, the performance drop is irrelevant.






                            share|improve this answer















                            Using a function converting an hexa string to byte, you could do



                            byte CDRIVES = hexStringToByteArray("e04fd020ea3a6910a2d808002b30309d");


                            I'd suggest you use the function defined by Dave L in Convert a string representation of a hex dump to a byte array using Java?



                            I insert it here for maximum readability :



                            public static byte hexStringToByteArray(String s) {
                            int len = s.length();
                            byte data = new byte[len / 2];
                            for (int i = 0; i < len; i += 2) {
                            data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                            + Character.digit(s.charAt(i+1), 16));
                            }
                            return data;
                            }


                            If you let CDRIVES static and final, the performance drop is irrelevant.







                            share|improve this answer














                            share|improve this answer



                            share|improve this answer








                            edited May 23 '17 at 12:10









                            Community

                            11




                            11










                            answered Jun 26 '12 at 13:43









                            Denys SéguretDenys Séguret

                            282k57590607




                            282k57590607

























                                59














                                byte myvar = "Any String you want".getBytes();


                                String literals can be escaped to provide any character:



                                byte CDRIVES = "u00e0u004fu00d0u0020u00eau003au0069u0010u00a2u00d8u0008u0000u002bu0030u0030u009d".getBytes();





                                share|improve this answer





















                                • 46





                                  Doesn't that turn the string "0000" to {0x30,0x30,0x30,0x30} (ASCII) rather than {0x00,0x00,0x00,0x00} (binary) as desired by the poster?

                                  – jww
                                  Aug 31 '14 at 15:57






                                • 7





                                  You're not answering the right question.

                                  – Sotirios Delimanolis
                                  May 16 '16 at 18:01






                                • 1





                                  And this garnered 52 upvotes?! Oi vey.

                                  – Lawrence Dol
                                  Jul 14 '16 at 2:30








                                • 2





                                  This is plain wrong.

                                  – rjha94
                                  Nov 9 '16 at 16:59






                                • 5





                                  Look at the question's title. Then look back at this answer. Now tell me, what's wrong about it? It might not solve the poster's particular issue, but it sure solved mine. I needed to transform a string into a byte array to use as a seed for a pseudorandom number generator and this worked like a charm.

                                  – e18r
                                  Sep 14 '18 at 15:55
















                                59














                                byte myvar = "Any String you want".getBytes();


                                String literals can be escaped to provide any character:



                                byte CDRIVES = "u00e0u004fu00d0u0020u00eau003au0069u0010u00a2u00d8u0008u0000u002bu0030u0030u009d".getBytes();





                                share|improve this answer





















                                • 46





                                  Doesn't that turn the string "0000" to {0x30,0x30,0x30,0x30} (ASCII) rather than {0x00,0x00,0x00,0x00} (binary) as desired by the poster?

                                  – jww
                                  Aug 31 '14 at 15:57






                                • 7





                                  You're not answering the right question.

                                  – Sotirios Delimanolis
                                  May 16 '16 at 18:01






                                • 1





                                  And this garnered 52 upvotes?! Oi vey.

                                  – Lawrence Dol
                                  Jul 14 '16 at 2:30








                                • 2





                                  This is plain wrong.

                                  – rjha94
                                  Nov 9 '16 at 16:59






                                • 5





                                  Look at the question's title. Then look back at this answer. Now tell me, what's wrong about it? It might not solve the poster's particular issue, but it sure solved mine. I needed to transform a string into a byte array to use as a seed for a pseudorandom number generator and this worked like a charm.

                                  – e18r
                                  Sep 14 '18 at 15:55














                                59












                                59








                                59







                                byte myvar = "Any String you want".getBytes();


                                String literals can be escaped to provide any character:



                                byte CDRIVES = "u00e0u004fu00d0u0020u00eau003au0069u0010u00a2u00d8u0008u0000u002bu0030u0030u009d".getBytes();





                                share|improve this answer















                                byte myvar = "Any String you want".getBytes();


                                String literals can be escaped to provide any character:



                                byte CDRIVES = "u00e0u004fu00d0u0020u00eau003au0069u0010u00a2u00d8u0008u0000u002bu0030u0030u009d".getBytes();






                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Jan 30 at 11:50









                                Nicolas

                                739821




                                739821










                                answered Jan 15 '14 at 18:50









                                petmezpetmez

                                1,04374




                                1,04374








                                • 46





                                  Doesn't that turn the string "0000" to {0x30,0x30,0x30,0x30} (ASCII) rather than {0x00,0x00,0x00,0x00} (binary) as desired by the poster?

                                  – jww
                                  Aug 31 '14 at 15:57






                                • 7





                                  You're not answering the right question.

                                  – Sotirios Delimanolis
                                  May 16 '16 at 18:01






                                • 1





                                  And this garnered 52 upvotes?! Oi vey.

                                  – Lawrence Dol
                                  Jul 14 '16 at 2:30








                                • 2





                                  This is plain wrong.

                                  – rjha94
                                  Nov 9 '16 at 16:59






                                • 5





                                  Look at the question's title. Then look back at this answer. Now tell me, what's wrong about it? It might not solve the poster's particular issue, but it sure solved mine. I needed to transform a string into a byte array to use as a seed for a pseudorandom number generator and this worked like a charm.

                                  – e18r
                                  Sep 14 '18 at 15:55














                                • 46





                                  Doesn't that turn the string "0000" to {0x30,0x30,0x30,0x30} (ASCII) rather than {0x00,0x00,0x00,0x00} (binary) as desired by the poster?

                                  – jww
                                  Aug 31 '14 at 15:57






                                • 7





                                  You're not answering the right question.

                                  – Sotirios Delimanolis
                                  May 16 '16 at 18:01






                                • 1





                                  And this garnered 52 upvotes?! Oi vey.

                                  – Lawrence Dol
                                  Jul 14 '16 at 2:30








                                • 2





                                  This is plain wrong.

                                  – rjha94
                                  Nov 9 '16 at 16:59






                                • 5





                                  Look at the question's title. Then look back at this answer. Now tell me, what's wrong about it? It might not solve the poster's particular issue, but it sure solved mine. I needed to transform a string into a byte array to use as a seed for a pseudorandom number generator and this worked like a charm.

                                  – e18r
                                  Sep 14 '18 at 15:55








                                46




                                46





                                Doesn't that turn the string "0000" to {0x30,0x30,0x30,0x30} (ASCII) rather than {0x00,0x00,0x00,0x00} (binary) as desired by the poster?

                                – jww
                                Aug 31 '14 at 15:57





                                Doesn't that turn the string "0000" to {0x30,0x30,0x30,0x30} (ASCII) rather than {0x00,0x00,0x00,0x00} (binary) as desired by the poster?

                                – jww
                                Aug 31 '14 at 15:57




                                7




                                7





                                You're not answering the right question.

                                – Sotirios Delimanolis
                                May 16 '16 at 18:01





                                You're not answering the right question.

                                – Sotirios Delimanolis
                                May 16 '16 at 18:01




                                1




                                1





                                And this garnered 52 upvotes?! Oi vey.

                                – Lawrence Dol
                                Jul 14 '16 at 2:30







                                And this garnered 52 upvotes?! Oi vey.

                                – Lawrence Dol
                                Jul 14 '16 at 2:30






                                2




                                2





                                This is plain wrong.

                                – rjha94
                                Nov 9 '16 at 16:59





                                This is plain wrong.

                                – rjha94
                                Nov 9 '16 at 16:59




                                5




                                5





                                Look at the question's title. Then look back at this answer. Now tell me, what's wrong about it? It might not solve the poster's particular issue, but it sure solved mine. I needed to transform a string into a byte array to use as a seed for a pseudorandom number generator and this worked like a charm.

                                – e18r
                                Sep 14 '18 at 15:55





                                Look at the question's title. Then look back at this answer. Now tell me, what's wrong about it? It might not solve the poster's particular issue, but it sure solved mine. I needed to transform a string into a byte array to use as a seed for a pseudorandom number generator and this worked like a charm.

                                – e18r
                                Sep 14 '18 at 15:55











                                30














                                In Java 6, there is a method doing exactly what you want:



                                private static final byte CDRIVES = javax.xml.bind.DatatypeConverter.parseHexBinary("e04fd020ea3a6910a2d808002b30309d")


                                Alternatively you could use Google Guava:



                                import com.google.common.io.BaseEncoding;
                                private static final byte CDRIVES = BaseEncoding.base16().lowerCase().decode("E04FD020ea3a6910a2d808002b30309d".toLowerCase());


                                The Guava method is overkill, when you are using small arrays. But Guava has also versions that can parse input streams. This is a nice feature when dealing with big hexadecimal inputs.






                                share|improve this answer


























                                • The Guava example doesn't quite work as written - it needs to be base16().lowerCase().decode(...) if you have lower case hex digits. docs.guava-libraries.googlecode.com/git/javadoc/com/google/…

                                  – Peter DeGlopper
                                  Sep 1 '15 at 21:43











                                • @PeterDeGlopper Good finding, I've updated the answer so the code now handles strings with both lower and upper case characters.

                                  – stefan.schwetschke
                                  Sep 2 '15 at 7:06











                                • javax.xml.bind was sadly removed in Java 9.

                                  – randomdude999
                                  Jan 5 at 22:02
















                                30














                                In Java 6, there is a method doing exactly what you want:



                                private static final byte CDRIVES = javax.xml.bind.DatatypeConverter.parseHexBinary("e04fd020ea3a6910a2d808002b30309d")


                                Alternatively you could use Google Guava:



                                import com.google.common.io.BaseEncoding;
                                private static final byte CDRIVES = BaseEncoding.base16().lowerCase().decode("E04FD020ea3a6910a2d808002b30309d".toLowerCase());


                                The Guava method is overkill, when you are using small arrays. But Guava has also versions that can parse input streams. This is a nice feature when dealing with big hexadecimal inputs.






                                share|improve this answer


























                                • The Guava example doesn't quite work as written - it needs to be base16().lowerCase().decode(...) if you have lower case hex digits. docs.guava-libraries.googlecode.com/git/javadoc/com/google/…

                                  – Peter DeGlopper
                                  Sep 1 '15 at 21:43











                                • @PeterDeGlopper Good finding, I've updated the answer so the code now handles strings with both lower and upper case characters.

                                  – stefan.schwetschke
                                  Sep 2 '15 at 7:06











                                • javax.xml.bind was sadly removed in Java 9.

                                  – randomdude999
                                  Jan 5 at 22:02














                                30












                                30








                                30







                                In Java 6, there is a method doing exactly what you want:



                                private static final byte CDRIVES = javax.xml.bind.DatatypeConverter.parseHexBinary("e04fd020ea3a6910a2d808002b30309d")


                                Alternatively you could use Google Guava:



                                import com.google.common.io.BaseEncoding;
                                private static final byte CDRIVES = BaseEncoding.base16().lowerCase().decode("E04FD020ea3a6910a2d808002b30309d".toLowerCase());


                                The Guava method is overkill, when you are using small arrays. But Guava has also versions that can parse input streams. This is a nice feature when dealing with big hexadecimal inputs.






                                share|improve this answer















                                In Java 6, there is a method doing exactly what you want:



                                private static final byte CDRIVES = javax.xml.bind.DatatypeConverter.parseHexBinary("e04fd020ea3a6910a2d808002b30309d")


                                Alternatively you could use Google Guava:



                                import com.google.common.io.BaseEncoding;
                                private static final byte CDRIVES = BaseEncoding.base16().lowerCase().decode("E04FD020ea3a6910a2d808002b30309d".toLowerCase());


                                The Guava method is overkill, when you are using small arrays. But Guava has also versions that can parse input streams. This is a nice feature when dealing with big hexadecimal inputs.







                                share|improve this answer














                                share|improve this answer



                                share|improve this answer








                                edited Aug 8 '16 at 15:49









                                Alex

                                15.1k104966




                                15.1k104966










                                answered Oct 8 '13 at 8:12









                                stefan.schwetschkestefan.schwetschke

                                8,02711827




                                8,02711827













                                • The Guava example doesn't quite work as written - it needs to be base16().lowerCase().decode(...) if you have lower case hex digits. docs.guava-libraries.googlecode.com/git/javadoc/com/google/…

                                  – Peter DeGlopper
                                  Sep 1 '15 at 21:43











                                • @PeterDeGlopper Good finding, I've updated the answer so the code now handles strings with both lower and upper case characters.

                                  – stefan.schwetschke
                                  Sep 2 '15 at 7:06











                                • javax.xml.bind was sadly removed in Java 9.

                                  – randomdude999
                                  Jan 5 at 22:02



















                                • The Guava example doesn't quite work as written - it needs to be base16().lowerCase().decode(...) if you have lower case hex digits. docs.guava-libraries.googlecode.com/git/javadoc/com/google/…

                                  – Peter DeGlopper
                                  Sep 1 '15 at 21:43











                                • @PeterDeGlopper Good finding, I've updated the answer so the code now handles strings with both lower and upper case characters.

                                  – stefan.schwetschke
                                  Sep 2 '15 at 7:06











                                • javax.xml.bind was sadly removed in Java 9.

                                  – randomdude999
                                  Jan 5 at 22:02

















                                The Guava example doesn't quite work as written - it needs to be base16().lowerCase().decode(...) if you have lower case hex digits. docs.guava-libraries.googlecode.com/git/javadoc/com/google/…

                                – Peter DeGlopper
                                Sep 1 '15 at 21:43





                                The Guava example doesn't quite work as written - it needs to be base16().lowerCase().decode(...) if you have lower case hex digits. docs.guava-libraries.googlecode.com/git/javadoc/com/google/…

                                – Peter DeGlopper
                                Sep 1 '15 at 21:43













                                @PeterDeGlopper Good finding, I've updated the answer so the code now handles strings with both lower and upper case characters.

                                – stefan.schwetschke
                                Sep 2 '15 at 7:06





                                @PeterDeGlopper Good finding, I've updated the answer so the code now handles strings with both lower and upper case characters.

                                – stefan.schwetschke
                                Sep 2 '15 at 7:06













                                javax.xml.bind was sadly removed in Java 9.

                                – randomdude999
                                Jan 5 at 22:02





                                javax.xml.bind was sadly removed in Java 9.

                                – randomdude999
                                Jan 5 at 22:02











                                7














                                You can use the Java UUID class to store these values, instead of byte arrays:



                                UUID

                                public UUID(long mostSigBits,
                                long leastSigBits)


                                Constructs a new UUID using the specified data. mostSigBits is used for the most significant 64 bits of the UUID and leastSigBits becomes the least significant 64 bits of the UUID.






                                share|improve this answer




























                                  7














                                  You can use the Java UUID class to store these values, instead of byte arrays:



                                  UUID

                                  public UUID(long mostSigBits,
                                  long leastSigBits)


                                  Constructs a new UUID using the specified data. mostSigBits is used for the most significant 64 bits of the UUID and leastSigBits becomes the least significant 64 bits of the UUID.






                                  share|improve this answer


























                                    7












                                    7








                                    7







                                    You can use the Java UUID class to store these values, instead of byte arrays:



                                    UUID

                                    public UUID(long mostSigBits,
                                    long leastSigBits)


                                    Constructs a new UUID using the specified data. mostSigBits is used for the most significant 64 bits of the UUID and leastSigBits becomes the least significant 64 bits of the UUID.






                                    share|improve this answer













                                    You can use the Java UUID class to store these values, instead of byte arrays:



                                    UUID

                                    public UUID(long mostSigBits,
                                    long leastSigBits)


                                    Constructs a new UUID using the specified data. mostSigBits is used for the most significant 64 bits of the UUID and leastSigBits becomes the least significant 64 bits of the UUID.







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Jun 26 '12 at 13:36









                                    JonJon

                                    2,3191923




                                    2,3191923























                                        2














                                        As far as a clean process is concerned you can use ByteArrayOutputStream object...



                                        ByteArrayOutputStream bObj = new ByteArrayOutputStream();
                                        bObj.reset();


                                        //write all the values to bObj one by one using



                                        bObj.write(byte value)


                                        // when done you can get the byte using



                                        CDRIVES = bObj.toByteArray();


                                        //than you can repeat the similar process for CMYDOCS and IEFRAME as well,



                                        NOTE This is not an efficient solution if you really have small array.






                                        share|improve this answer






























                                          2














                                          As far as a clean process is concerned you can use ByteArrayOutputStream object...



                                          ByteArrayOutputStream bObj = new ByteArrayOutputStream();
                                          bObj.reset();


                                          //write all the values to bObj one by one using



                                          bObj.write(byte value)


                                          // when done you can get the byte using



                                          CDRIVES = bObj.toByteArray();


                                          //than you can repeat the similar process for CMYDOCS and IEFRAME as well,



                                          NOTE This is not an efficient solution if you really have small array.






                                          share|improve this answer




























                                            2












                                            2








                                            2







                                            As far as a clean process is concerned you can use ByteArrayOutputStream object...



                                            ByteArrayOutputStream bObj = new ByteArrayOutputStream();
                                            bObj.reset();


                                            //write all the values to bObj one by one using



                                            bObj.write(byte value)


                                            // when done you can get the byte using



                                            CDRIVES = bObj.toByteArray();


                                            //than you can repeat the similar process for CMYDOCS and IEFRAME as well,



                                            NOTE This is not an efficient solution if you really have small array.






                                            share|improve this answer















                                            As far as a clean process is concerned you can use ByteArrayOutputStream object...



                                            ByteArrayOutputStream bObj = new ByteArrayOutputStream();
                                            bObj.reset();


                                            //write all the values to bObj one by one using



                                            bObj.write(byte value)


                                            // when done you can get the byte using



                                            CDRIVES = bObj.toByteArray();


                                            //than you can repeat the similar process for CMYDOCS and IEFRAME as well,



                                            NOTE This is not an efficient solution if you really have small array.







                                            share|improve this answer














                                            share|improve this answer



                                            share|improve this answer








                                            edited Dec 18 '15 at 5:32

























                                            answered Jun 26 '12 at 13:40









                                            AmitAmit

                                            7,4891459136




                                            7,4891459136























                                                1














                                                My preferred option in this circumstance is to use org.apache.commons.codec.binary.Hex which has useful APIs for converting between Stringy hex and binary. For example:




                                                1. Hex.decodeHex(char data) which throws a DecoderException if there are non-hex characters in the array, or if there are an odd number of characters.


                                                2. Hex.encodeHex(byte data) is the counterpart to the decode method above, and spits out the char.


                                                3. Hex.encodeHexString(byte data) which converts back from a byte array to a String.



                                                Usage: Hex.decodeHex("dd645a2564cbe648c8336d2be5eafaa6".toCharArray())






                                                share|improve this answer






























                                                  1














                                                  My preferred option in this circumstance is to use org.apache.commons.codec.binary.Hex which has useful APIs for converting between Stringy hex and binary. For example:




                                                  1. Hex.decodeHex(char data) which throws a DecoderException if there are non-hex characters in the array, or if there are an odd number of characters.


                                                  2. Hex.encodeHex(byte data) is the counterpart to the decode method above, and spits out the char.


                                                  3. Hex.encodeHexString(byte data) which converts back from a byte array to a String.



                                                  Usage: Hex.decodeHex("dd645a2564cbe648c8336d2be5eafaa6".toCharArray())






                                                  share|improve this answer




























                                                    1












                                                    1








                                                    1







                                                    My preferred option in this circumstance is to use org.apache.commons.codec.binary.Hex which has useful APIs for converting between Stringy hex and binary. For example:




                                                    1. Hex.decodeHex(char data) which throws a DecoderException if there are non-hex characters in the array, or if there are an odd number of characters.


                                                    2. Hex.encodeHex(byte data) is the counterpart to the decode method above, and spits out the char.


                                                    3. Hex.encodeHexString(byte data) which converts back from a byte array to a String.



                                                    Usage: Hex.decodeHex("dd645a2564cbe648c8336d2be5eafaa6".toCharArray())






                                                    share|improve this answer















                                                    My preferred option in this circumstance is to use org.apache.commons.codec.binary.Hex which has useful APIs for converting between Stringy hex and binary. For example:




                                                    1. Hex.decodeHex(char data) which throws a DecoderException if there are non-hex characters in the array, or if there are an odd number of characters.


                                                    2. Hex.encodeHex(byte data) is the counterpart to the decode method above, and spits out the char.


                                                    3. Hex.encodeHexString(byte data) which converts back from a byte array to a String.



                                                    Usage: Hex.decodeHex("dd645a2564cbe648c8336d2be5eafaa6".toCharArray())







                                                    share|improve this answer














                                                    share|improve this answer



                                                    share|improve this answer








                                                    edited Oct 13 '16 at 10:19

























                                                    answered Oct 13 '16 at 9:25









                                                    rbrtlrbrtl

                                                    508419




                                                    508419























                                                        1














                                                        A solution with no libraries, dynamic length returned, unsigned integer interpretation (not two's complement)



                                                            public static byte numToBytes(int num){
                                                        if(num == 0){
                                                        return new byte{};
                                                        }else if(num < 256){
                                                        return new byte{ (byte)(num) };
                                                        }else if(num < 65536){
                                                        return new byte{ (byte)(num >>> 8),(byte)num };
                                                        }else if(num < 16777216){
                                                        return new byte{ (byte)(num >>> 16),(byte)(num >>> 8),(byte)num };
                                                        }else{ // up to 2,147,483,647
                                                        return new byte{ (byte)(num >>> 24),(byte)(num >>> 16),(byte)(num >>> 8),(byte)num };
                                                        }
                                                        }





                                                        share|improve this answer




























                                                          1














                                                          A solution with no libraries, dynamic length returned, unsigned integer interpretation (not two's complement)



                                                              public static byte numToBytes(int num){
                                                          if(num == 0){
                                                          return new byte{};
                                                          }else if(num < 256){
                                                          return new byte{ (byte)(num) };
                                                          }else if(num < 65536){
                                                          return new byte{ (byte)(num >>> 8),(byte)num };
                                                          }else if(num < 16777216){
                                                          return new byte{ (byte)(num >>> 16),(byte)(num >>> 8),(byte)num };
                                                          }else{ // up to 2,147,483,647
                                                          return new byte{ (byte)(num >>> 24),(byte)(num >>> 16),(byte)(num >>> 8),(byte)num };
                                                          }
                                                          }





                                                          share|improve this answer


























                                                            1












                                                            1








                                                            1







                                                            A solution with no libraries, dynamic length returned, unsigned integer interpretation (not two's complement)



                                                                public static byte numToBytes(int num){
                                                            if(num == 0){
                                                            return new byte{};
                                                            }else if(num < 256){
                                                            return new byte{ (byte)(num) };
                                                            }else if(num < 65536){
                                                            return new byte{ (byte)(num >>> 8),(byte)num };
                                                            }else if(num < 16777216){
                                                            return new byte{ (byte)(num >>> 16),(byte)(num >>> 8),(byte)num };
                                                            }else{ // up to 2,147,483,647
                                                            return new byte{ (byte)(num >>> 24),(byte)(num >>> 16),(byte)(num >>> 8),(byte)num };
                                                            }
                                                            }





                                                            share|improve this answer













                                                            A solution with no libraries, dynamic length returned, unsigned integer interpretation (not two's complement)



                                                                public static byte numToBytes(int num){
                                                            if(num == 0){
                                                            return new byte{};
                                                            }else if(num < 256){
                                                            return new byte{ (byte)(num) };
                                                            }else if(num < 65536){
                                                            return new byte{ (byte)(num >>> 8),(byte)num };
                                                            }else if(num < 16777216){
                                                            return new byte{ (byte)(num >>> 16),(byte)(num >>> 8),(byte)num };
                                                            }else{ // up to 2,147,483,647
                                                            return new byte{ (byte)(num >>> 24),(byte)(num >>> 16),(byte)(num >>> 8),(byte)num };
                                                            }
                                                            }






                                                            share|improve this answer












                                                            share|improve this answer



                                                            share|improve this answer










                                                            answered Nov 10 '17 at 20:49









                                                            ZMittonZMitton

                                                            1597




                                                            1597























                                                                0














                                                                You can use this utility function:



                                                                public static byte fromHexString(String src) {
                                                                byte biBytes = new BigInteger("10" + src.replaceAll("\s", ""), 16).toByteArray();
                                                                return Arrays.copyOfRange(biBytes, 1, biBytes.length);
                                                                }


                                                                Unlike variants of Denys Séguret and stefan.schwetschke, it allows inserting separator symbols (spaces, tabs, etc.) into the input string, making it more readable.



                                                                Example of usage:



                                                                private static final byte CDRIVES
                                                                = fromHexString("e0 4f d0 20 ea 3a 69 10 a2 d8 08 00 2b 30 30 9d");
                                                                private static final byte CMYDOCS
                                                                = fromHexString("BA8A0D4525ADD01198A80800361B1103");
                                                                private static final byte IEFRAME
                                                                = fromHexString("80531c87 a0426910 a2ea0800 2b30309d");





                                                                share|improve this answer




























                                                                  0














                                                                  You can use this utility function:



                                                                  public static byte fromHexString(String src) {
                                                                  byte biBytes = new BigInteger("10" + src.replaceAll("\s", ""), 16).toByteArray();
                                                                  return Arrays.copyOfRange(biBytes, 1, biBytes.length);
                                                                  }


                                                                  Unlike variants of Denys Séguret and stefan.schwetschke, it allows inserting separator symbols (spaces, tabs, etc.) into the input string, making it more readable.



                                                                  Example of usage:



                                                                  private static final byte CDRIVES
                                                                  = fromHexString("e0 4f d0 20 ea 3a 69 10 a2 d8 08 00 2b 30 30 9d");
                                                                  private static final byte CMYDOCS
                                                                  = fromHexString("BA8A0D4525ADD01198A80800361B1103");
                                                                  private static final byte IEFRAME
                                                                  = fromHexString("80531c87 a0426910 a2ea0800 2b30309d");





                                                                  share|improve this answer


























                                                                    0












                                                                    0








                                                                    0







                                                                    You can use this utility function:



                                                                    public static byte fromHexString(String src) {
                                                                    byte biBytes = new BigInteger("10" + src.replaceAll("\s", ""), 16).toByteArray();
                                                                    return Arrays.copyOfRange(biBytes, 1, biBytes.length);
                                                                    }


                                                                    Unlike variants of Denys Séguret and stefan.schwetschke, it allows inserting separator symbols (spaces, tabs, etc.) into the input string, making it more readable.



                                                                    Example of usage:



                                                                    private static final byte CDRIVES
                                                                    = fromHexString("e0 4f d0 20 ea 3a 69 10 a2 d8 08 00 2b 30 30 9d");
                                                                    private static final byte CMYDOCS
                                                                    = fromHexString("BA8A0D4525ADD01198A80800361B1103");
                                                                    private static final byte IEFRAME
                                                                    = fromHexString("80531c87 a0426910 a2ea0800 2b30309d");





                                                                    share|improve this answer













                                                                    You can use this utility function:



                                                                    public static byte fromHexString(String src) {
                                                                    byte biBytes = new BigInteger("10" + src.replaceAll("\s", ""), 16).toByteArray();
                                                                    return Arrays.copyOfRange(biBytes, 1, biBytes.length);
                                                                    }


                                                                    Unlike variants of Denys Séguret and stefan.schwetschke, it allows inserting separator symbols (spaces, tabs, etc.) into the input string, making it more readable.



                                                                    Example of usage:



                                                                    private static final byte CDRIVES
                                                                    = fromHexString("e0 4f d0 20 ea 3a 69 10 a2 d8 08 00 2b 30 30 9d");
                                                                    private static final byte CMYDOCS
                                                                    = fromHexString("BA8A0D4525ADD01198A80800361B1103");
                                                                    private static final byte IEFRAME
                                                                    = fromHexString("80531c87 a0426910 a2ea0800 2b30309d");






                                                                    share|improve this answer












                                                                    share|improve this answer



                                                                    share|improve this answer










                                                                    answered Nov 25 '18 at 1:11









                                                                    John McClaneJohn McClane

                                                                    1,5502421




                                                                    1,5502421























                                                                        -2














                                                                        private static final int CDRIVES = new int {0xe0, 0xf4, ...};


                                                                        and after access convert to byte.






                                                                        share|improve this answer




























                                                                          -2














                                                                          private static final int CDRIVES = new int {0xe0, 0xf4, ...};


                                                                          and after access convert to byte.






                                                                          share|improve this answer


























                                                                            -2












                                                                            -2








                                                                            -2







                                                                            private static final int CDRIVES = new int {0xe0, 0xf4, ...};


                                                                            and after access convert to byte.






                                                                            share|improve this answer













                                                                            private static final int CDRIVES = new int {0xe0, 0xf4, ...};


                                                                            and after access convert to byte.







                                                                            share|improve this answer












                                                                            share|improve this answer



                                                                            share|improve this answer










                                                                            answered Sep 5 '17 at 11:08









                                                                            FrankieFrankie

                                                                            1




                                                                            1

















                                                                                protected by Nilesh Rathod May 5 '18 at 10:35



                                                                                Thank you for your interest in this question.
                                                                                Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).



                                                                                Would you like to answer one of these unanswered questions instead?



                                                                                這個網誌中的熱門文章

                                                                                Xamarin.form Move up view when keyboard appear

                                                                                Post-Redirect-Get with Spring WebFlux and Thymeleaf

                                                                                Anylogic : not able to use stopDelay()