I would like to be able to convert a String (with words/letters) to other forms, like binary. How would I go about doing this. I am coding in BLUEJ (Java). Thanks
A String
in Java can be converted to binary with its getBytes(String)
method.
The argument to this method is a "character-encoding"; this is the name a standardized mapping between a character and a sequence of bytes. Often, each character is encoded to a single byte, but there aren't enough unique byte values to represent every character in every language. Other encodings use multiple bytes, so they can handle a wider range of characters.
Usually, the encoding to use will be specified by some standard or protocol that you are implementing. If you are creating your own interface, and have the freedom to choose, "UTF-8" is an easy, safe, and widely supported encoding.
- It's easy, because rather than including some way to note the encoding of each message, you can default to UTF-8.
- It's safe, because UTF-8 can encode any character that can be used in a Java character string.
- It's widely supported, because it is one of a small handful of character encodings that is required to be present in any Java implementation, all the way down to J2ME. Most other platforms support it too, and it's used as a default in standards like XML.
The usual way is to use String#getBytes()
to get the underlying bytes and then present those bytes in some other form (hex, binary whatever).
Note that getBytes()
uses the default charset, so if you want the string converted to some specific character encoding, you should use getBytes(String encoding)
instead, but many times (esp when dealing with ASCII) getBytes()
is enough (and has the advantage of not throwing a checked exception).
For specific conversion to binary, here is an example:
String s = "foo";
byte[] bytes = s.getBytes();
StringBuilder binary = new StringBuilder();
for (byte b : bytes)
{
int val = b;
for (int i = 0; i < 8; i++)
{
binary.append((val & 128) == 0 ? 0 : 1);
val <<= 1;
}
binary.append(' ');
}
System.out.println("'" + s + "' to binary: " + binary);
Running this example will yield:
'foo' to binary: 01100110 01101111 01101111
A shorter example
private static final Charset UTF_8 = Charset.forName("UTF-8");
String text = "Hello World!";
byte[] bytes = text.getBytes(UTF_8);
System.out.println("bytes= "+Arrays.toString(bytes));
System.out.println("text again= "+new String(bytes, UTF_8));
prints
bytes= [72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33]
text again= Hello World!
**public class HexadecimalToBinaryAndLong{
public static void main(String[] args) throws IOException{
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
System.out.println("Enter the hexa value!");
String hex = bf.readLine();
int i = Integer.parseInt(hex); //hex to decimal
String by = Integer.toBinaryString(i); //decimal to binary
System.out.println("This is Binary: " + by);
}
}