Java ByteBuffer to String

后端 未结 10 1603
一生所求
一生所求 2020-12-07 21:30

Is this a correct approach to convert ByteBuffer to String in this way,

String k = \"abcd\";
ByteBuffer b = ByteBuffer.wrap(k.getBytes());
String v = new Str         


        
10条回答
  •  佛祖请我去吃肉
    2020-12-07 22:02

    Convert a String to ByteBuffer, then from ByteBuffer back to String using Java:

    import java.nio.charset.Charset;
    import java.nio.*;
    
    String babel = "obufscate thdé alphebat and yolo!!";
    System.out.println(babel);
    //Convert string to ByteBuffer:
    ByteBuffer babb = Charset.forName("UTF-8").encode(babel);
    try{
        //Convert ByteBuffer to String
        System.out.println(new String(babb.array(), "UTF-8"));
    }
    catch(Exception e){
        e.printStackTrace();
    }
    

    Which prints the printed bare string first, and then the ByteBuffer casted to array():

    obufscate thdé alphebat and yolo!!
    obufscate thdé alphebat and yolo!!
    

    Also this was helpful for me, reducing the string to primitive bytes can help inspect what's going on:

    String text = "こんにちは";
    //convert utf8 text to a byte array
    byte[] array = text.getBytes("UTF-8");
    //convert the byte array back to a string as UTF-8
    String s = new String(array, Charset.forName("UTF-8"));
    System.out.println(s);
    //forcing strings encoded as UTF-8 as an incorrect encoding like
    //say ISO-8859-1 causes strange and undefined behavior
    String sISO = new String(array, Charset.forName("ISO-8859-1"));
    System.out.println(sISO);
    

    Prints your string interpreted as UTF-8, and then again as ISO-8859-1:

    こんにちは
    ããã«ã¡ã¯
    

提交回复
热议问题