Answers for "create bytebuffer from string"

1

convert bytebuffer to string

String s = StandardCharsets.UTF_8.decode(byteBuffer).toString();
Posted by: Guest on March-31-2021
0

Java String to ByteBuffer conversion

public static Charset charset = Charset.forName("UTF-8");
public static CharsetEncoder encoder = charset.newEncoder();
public static CharsetDecoder decoder = charset.newDecoder();

public static ByteBuffer str_to_bb(String msg){
  try{
    return encoder.encode(CharBuffer.wrap(msg));
  }catch(Exception e){e.printStackTrace();}
  return null;
}

public static String bb_to_str(ByteBuffer buffer){
  String data = "";
  try{
    int old_position = buffer.position();
    data = decoder.decode(buffer).toString();
    // reset buffer's position to its original so it is not altered:
    buffer.position(old_position);  
  }catch (Exception e){
    e.printStackTrace();
    return "";
  }
  return data;
}
Posted by: Guest on June-28-2021

Code answers related to "create bytebuffer from string"

Code answers related to "Java"

Java Answers by Framework

Browse Popular Code Answers by Language