-1

What kind of algorithm/method would you use to change a simple string to binary and vice-versa (In Java)?

MrLolEthan
  • 76
  • 3
  • 9

3 Answers3

2

str.getBytes() returns byte array,

String(byte[], java.lang.String) creates new String instance from byte array an charset.

I hope this helps...

AlexR
  • 114,158
  • 16
  • 130
  • 208
0

Binary to text - Base64 encoding. Text to binary - Base64 decoding.

RaviH
  • 3,544
  • 2
  • 15
  • 14
0

You can use BigInteger to convert it to Hex and back.

    byte [] binary = new byte[] {0,1,2,3,4,5};
    System.out.println("Binary: "+Arrays.toString(binary));
    String asText = new BigInteger(binary).toString(16);
    System.out.println("Text: "+asText);
    byte[] asBinary = new BigInteger(asText, 16).toByteArray();
    System.out.println("Back to Binary: "+Arrays.toString(asBinary));

prints:

Binary: [0, 1, 2, 3, 4, 5]
Text: 102030405
Back to Binary: [1, 2, 3, 4, 5]
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213