Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 9 of 9

Thread: [Asking] Convert String to Byte Array

  1. #1
    Member
    Join Date
    Sep 2012
    Posts
    30
    My Mood
    Cool
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default [Asking] Convert String to Byte Array

    Hi everyone,

    I get confused when to convert string to byte array. let's go to the code

    String strKey = "BDE540BD7E91EDACA3B0125FE004F52C";
    byte[] bytKey = strKey.getBytes();

    System.out.println("len "bytKey.length);

    When I run the code, the length of bytKey is 32 not 16. I want the length of bytKey is 16.
    So in array should be like this ;
    bytKey[0] = 'BD';
    bytKey[1] = 'E5';
    ......
    ......
    bytKey[15] = '2C';


    Please share me if anyone know how to solve this,

    thanks


  2. #2
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: [Asking] Convert String to Byte Array

    I'm not sure I understand - the String is 32 characters long. Not sure how you expect the bytes of the information of the String any less than 32. That being said, read the API for the getBytes methods of String, there are ways to specify a Charset that differs from your default OS Charset.

  3. #3
    Member
    Join Date
    Sep 2012
    Posts
    30
    My Mood
    Cool
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: [Asking] Convert String to Byte Array

    Hi, copeg..

    I expect the byte array from the String , may be I'm wrong about array example writing.

    The arrray should be like this :

    bytKey[0] = 0xBD;
    bytKey[1] = 0xE5;
    ........
    ........
    bytKey[15] = 0x2C;

    Btw, I already use utf8, but the length still 32.

    Please help me

  4. #4
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: [Asking] Convert String to Byte Array

    You have a string of length 32. Each character of that string is 1 byte (8 bits) per character - hence an array of 32 bytes (based upon the encoding you are using - the default for your system and most likely some type of ASCII character code). I do not know of an encoding which packs the characters as 2 characters/byte. What is wrong with the current encoding?

  5. #5
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: [Asking] Convert String to Byte Array

    Declare an array of bytes. The length of the byte array is equal to the String length()/2.
    byte [] byteArray = new byte[strKey.length()/2];



    Make a loop that goes through the string two chars at a time:
        for (int i = 0; i < strKey.length(); i+= 2)

    Inside the loop

    1. Extract two chars at position i and position i+1 in the String

      Set char1 = the character of strKey at index value i
      Set char2 = the character of strKey at index value i+1


    2. Convert each char to an integer with the value of that character, radix 16
      int1 = Character.digit(char1,16)
      Similarly for int2


    3. Convert the two hex values to an 8-bit byte
      intValue = int1*16+int2


    4. set byteArray[i/2] equal to the value of intValue, cast to a byte.



    Cheers!

    Z
    Last edited by Zaphod_b; October 29th, 2012 at 09:11 PM.

  6. The Following User Says Thank You to Zaphod_b For This Useful Post:

    ardisamudra (October 29th, 2012)

  7. #6
    Member
    Join Date
    Sep 2012
    Posts
    30
    My Mood
    Cool
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: [Asking] Convert String to Byte Array

    Hi copeg...
    The current encoding have length 32. So in the array should be like this

    bytKey[0] = 0x42;
    bytKey[1] = 0x44;
    bytKey[2] = 0x45;
    ........
    ........
    bytKey[31] = 0x43;

    But actually that isn't what I want. The byte array what I want which represent the hexadecimal as 2 characters/byte.

    bytKey[0] = 0xBD;
    bytKey[1] = 0xE5;
    ........
    ........
    bytKey[15] = 0x2C;

    I got confused how to use bitwise operator.

  8. #7
    Member
    Join Date
    Sep 2012
    Posts
    30
    My Mood
    Cool
    Thanks
    1
    Thanked 1 Time in 1 Post

    Default Re: [Asking] Convert String to Byte Array

    Hi Zaphod....

    Thanks for your code, so the full code perhaps like this below

    public static void convertStr2Byte() {
            String strKey = "BDE540BD7E91EDACA3B0125FE004F52C";
            byte[] byteArray = new byte[strKey.length()/2];
     
            for(int i = 0 ; i < strKey.length(); i+=2) {
                char ch1 = strKey.charAt(i);
                char ch2 = strKey.charAt(i+1);
     
                int int1 = Character.digit(ch1, 16);
                int int2 = Character.digit(ch2, 16);
     
                int value = int1 * 16 + int2;
                byteArray[i/2] = (byte) value;
                System.out.println("byteArray["+i+"] "+byteArray[i/2]);
            }
        }
    thanks to copeg to explain more details about byte array
    Last edited by jps; October 31st, 2012 at 01:04 AM. Reason: added code tags

  9. #8
    Member
    Join Date
    Jun 2012
    Location
    Left Coast, USA
    Posts
    451
    My Mood
    Mellow
    Thanks
    1
    Thanked 97 Times in 88 Posts

    Default Re: [Asking] Convert String to Byte Array

    As a matter of conventional programming style, I think it would be better to let the convertStr2Byte() method convert and return the array of bytes and leave printing for the calling function:
    public class TestStr2Byte {
        public static void main(String [] args) {
     
            String strKey = "BDE540BD7E91EDACA3B0125FE004F52C";
            byte [] bytes = convertStr2Bytes(strKey);
     
            System.out.printf("The String    : %s\n", strKey);
            System.out.print("The hex bytes : ");
     
            for (int i = 0; i < bytes.length; i++) {
                System.out.printf("%02X ", bytes[i]);
            }
            System.out.println();
     
        } // End main
     
        // The function should do one thing: Convert.
        public static byte [] convertStr2Bytes(String str) {
            byte [] byteArray = new byte[str.length()/2];
     
            //
            // Put your code to convert.  Don't print
            //
            return byteArray;
        }// End convertStr2Bytes

    Or some such thing.

    Output:
    The String    : BDE540BD7E91EDACA3B0125FE004F52C
    The hex bytes : BD E5 40 BD 7E 91 ED AC A3 B0 12 5F E0 04 F5 2C


    Cheers!

    Z
    Last edited by Zaphod_b; October 30th, 2012 at 08:31 AM.

  10. #9
    Administrator copeg's Avatar
    Join Date
    Oct 2009
    Location
    US
    Posts
    5,320
    Thanks
    181
    Thanked 833 Times in 772 Posts
    Blog Entries
    5

    Default Re: [Asking] Convert String to Byte Array

    I may have missed the full question when reading your posts as the word 'hex' was never used until Zaphod's posts rang a bell in my head...so your string is hexadecimal? An alternative to the method above is to loop over each hex value (every 2 chars of the string) and use Integer.parseInt with a radix of 16 to get the byte value
    Last edited by copeg; October 30th, 2012 at 10:03 AM.

Similar Threads

  1. How to convert String array to Integer array...?'
    By suyog53 in forum File I/O & Other I/O Streams
    Replies: 2
    Last Post: September 25th, 2012, 08:50 AM
  2. I need to convert String into array
    By talha07 in forum Collections and Generics
    Replies: 1
    Last Post: October 9th, 2011, 01:58 PM
  3. How Convert a Byte array to a image format
    By perlWhite in forum Algorithms & Recursion
    Replies: 7
    Last Post: February 19th, 2011, 03:16 PM
  4. [SOLVED] utf-16 byte[] to string conversion
    By Gerhardl in forum What's Wrong With My Code?
    Replies: 5
    Last Post: February 25th, 2010, 07:06 AM
  5. Convert Vector to Byte Array
    By perlWhite in forum Java Theory & Questions
    Replies: 0
    Last Post: August 25th, 2009, 05:45 AM