From 6ab8d2dab2e1430783903d8aa28411d36e0ead1c Mon Sep 17 00:00:00 2001 From: Shekhar Gulati Date: Mon, 16 May 2016 18:46:41 +0530 Subject: [PATCH] Added support for `binDecode` --- src/main/java/strman/Strman.java | 17 +++++++++++++++++ src/test/java/strman/StrmanTest.java | 12 ++++++++++++ 2 files changed, 29 insertions(+) diff --git a/src/main/java/strman/Strman.java b/src/main/java/strman/Strman.java index 3bf9d17..47834f9 100644 --- a/src/main/java/strman/Strman.java +++ b/src/main/java/strman/Strman.java @@ -7,6 +7,8 @@ import java.util.StringJoiner; import java.util.function.Predicate; import java.util.function.Supplier; +import static java.util.stream.Collectors.joining; + /** * A String manipulation library without any dependencies */ @@ -317,6 +319,21 @@ public abstract class Strman { return Base64.getEncoder().encodeToString(value.getBytes()); } + /** + * Convert binary unicode (16 digits) string to string chars + * + * @param value The value to decode + * @return The decoded String + */ + public static String binDecode(final String value) { + validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER); + return Arrays + .stream(value.split("(?<=\\G.{16})")) + .map(data -> String.valueOf(Character.toChars(Integer.parseInt(data,2)))) + .collect(joining()); + } + + private static long countSubstr(String value, String subStr, boolean allowOverlapping, long count) { int position = value.indexOf(subStr); if (position == -1) { diff --git a/src/test/java/strman/StrmanTest.java b/src/test/java/strman/StrmanTest.java index ae3e1c8..90993fc 100644 --- a/src/test/java/strman/StrmanTest.java +++ b/src/test/java/strman/StrmanTest.java @@ -262,6 +262,18 @@ public class StrmanTest { assertThat(base64Encode("bar"), equalTo("YmFy")); assertThat(base64Encode("bár!"), equalTo("YsOhciE=")); assertThat(base64Encode("漢"), equalTo("5ryi")); + } + + @Test + public void binDecode_shouldDecodeABinaryStringToAValue() throws Exception { + assertThat( + binDecode("000000000111001100000000011101000000000001110010000000000110110100000000011000010000000001101110"), + equalTo("strman")); + + assertThat(binDecode("0110111100100010"),equalTo("漢")); + assertThat(binDecode("0000000001000001"),equalTo("A")); + assertThat(binDecode("0000000011000001"),equalTo("Á")); + assertThat(binDecode("00000000010000010000000001000001"),equalTo("AA")); } } \ No newline at end of file