Groovy web console

subscribe to the feed Subscribe
to this
site

String to Binary and vice versa

Published 1 month ago by Ram with tags String to Binary
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import java.nio.charset.Charset;
import java.nio.charset. StandardCharsets;

String string = "The girl on the red dress.";
byte[] byteString = string.getBytes(Charset.forName("UTF-8"));
System.out.println("[Input String]: " + string);
System.out.println("[Encoded String UTF-8]: " + byteString);

BigInteger biStr = new BigInteger(byteString);
System.out.println("binary: " + biStr.toString(2)); // binary
//System.out.println("hex: " + biStr.toString(16));   // hex or base 16
//System.out.println("dec: " + biStr.toString(10));  // this is base 10
//String val = biStr.toString(2).getBytes("UTF-8");
//System.out.println("binary to byte: " + val);
byte[] bid = biStr.toByteArray();
 
System.out.println("Output bidString UTF-8: " + bid);
String s = new String(bid);  
System.out.println("Output String UTF-8: " + s);