简体   繁体   中英

Conversion from String to Byte in java

I am converting a Byte data to String and this string back to byte.However when i try to convert this string back to byte i am unable to retrieve the byte data back.I know i am doing something very silly some were.Can somebody please let me know what is the error?Following is my code in java

Log.e("byte data",""+byte_data[3]);  //70
Log.e("data in string",""+Integer.toBinaryString(byte_data[3]));  //1000110
String data=Integer.toBinaryString(byte_song[3]);
Log.e("byte data",""+data.getBytes());

However dat.getBytes() returns [B@414eaa48 however it should have returned me 70.

getBytes returns a byte array, and the toString methods of arrays do not display their contents (which can be annoying at times). Try Arrays.toString to show the contents of arrays instead. Note that for an object x , "" + x is equivalent to x.toString() .

dat.getBytes() provides an array of bytes , which is itself an object in java. Whenever you try to print out that object or call toString() , it calls the toString() method of java.lang.Object class. In java.lang.Object class toString() is defined in following way:

public String  toString() {
        return getClass().getName() + "@" + Integer.toHexString(hashCode());
    }

That's why you are getting such output. To achieve what you want
Log.e("byte data",""+dat.getBytes()); should be changed to
Log.e("byte data",""+java.util.Arrays.toString(dat.getBytes()));
UPDATE
To get 70 back you should use:
Log.e("byte data",""+Integer.parseInt(String.valueOf(byte_data[3]),10));
OR
Log.e("byte data",""+Integer.parseInt(data,2));
To know how it worked Look at here Integer.parseInt(String s, int radix)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM