Labba
Labba

Reputation: 131

Convert a string of bits to unicode character in java

I'm trying to convert a string of bits into Unicode characters in java. Problem is that I only get chines signs etc.

String bits = "01010011011011100110000101110010"

Anyone know how to do this?

Upvotes: 2

Views: 1158

Answers (1)

Krzysztof Krasoń
Krzysztof Krasoń

Reputation: 27496

Values <= 32bits

Use Integer.parseInt to parse the binary string, then convert it to byte array (using ByteBuffer) and finally convert byte array to String:

String bits = "01010011011011100110000101110010"
new String(
    ByteBuffer.allocate(4).putInt(
        Integer.parseInt(bits, 2)
    ).array(), 
    StandardCharsets.UTF_8
);

Values > 32bits

For arbitrary large bits String you can use also BigInteger:

new String(
    new BigInteger(bits, 2).toByteArray(),
    StandardCharsets.UTF_8
);

Result

Snar

Upvotes: 4

Related Questions