简体   繁体   中英

how to convert string to byte in java?

How to make string "01001000"(for example) to byte and convert it to string.

Example :

if string = "0110000101100010" then output must be "ab"

because a == 01100001 and b == 01100010

something like this:

      String[] array = {"01100001","01100010"};
      StringBuilder sb = new StringBuilder();
      for( String string : array ) {
          sb.append( (char)Integer.parseInt( string, 2 ) );
      }

or if you have one String which has exact 8-bit * x letter.

    String source = "0110000101100010";
    StringBuilder sb = new StringBuilder();
    for( int i = 0; i < source.length(); i= i+8 ) {
        sb.append( (char)Integer.parseInt( source.substring( i, i+8 ), 2 ) );
    }
StringBuilder sb = new StringBuilder();
for(String str : "0110000101100010".split("(?<=\\G.{8})")){
    sb.append((char)Byte.parseByte(str,2));
}
System.out.println(sb.toString());

Will output --> ab

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