mirror of
https://github.com/shekhargulati/strman-java.git
synced 2026-10-17 21:03:58 +00:00
Added support for binEncode
This commit is contained in:
@@ -6,6 +6,7 @@ import java.util.Optional;
|
||||
import java.util.StringJoiner;
|
||||
import java.util.function.Predicate;
|
||||
import java.util.function.Supplier;
|
||||
import java.util.stream.Stream;
|
||||
|
||||
import static java.util.stream.Collectors.joining;
|
||||
|
||||
@@ -329,10 +330,29 @@ public abstract class Strman {
|
||||
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))))
|
||||
.map(data -> String.valueOf(Character.toChars(Integer.parseInt(data, 2))))
|
||||
.collect(joining());
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert string chars to binary unicode (16 digits)
|
||||
*
|
||||
* @param value The value to encode
|
||||
* @return String in binary format
|
||||
*/
|
||||
public static String binEncode(final String value) {
|
||||
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
|
||||
return value.chars().mapToObj(ch -> leftPad(Integer.toBinaryString(ch), "0", 16)).collect(joining());
|
||||
}
|
||||
|
||||
public static String leftPad(String value, String pad, int length) {
|
||||
validate(value, NULL_STRING_PREDICATE, NULL_STRING_MSG_SUPPLIER);
|
||||
if (value.length() >= length) {
|
||||
return value;
|
||||
}
|
||||
return append(Stream.generate(() -> pad).limit(length - value.length()).collect(joining()), value);
|
||||
}
|
||||
|
||||
|
||||
private static long countSubstr(String value, String subStr, boolean allowOverlapping, long count) {
|
||||
int position = value.indexOf(subStr);
|
||||
|
||||
@@ -270,10 +270,17 @@ public class StrmanTest {
|
||||
binDecode("000000000111001100000000011101000000000001110010000000000110110100000000011000010000000001101110"),
|
||||
equalTo("strman"));
|
||||
|
||||
assertThat(binDecode("0110111100100010"),equalTo("漢"));
|
||||
assertThat(binDecode("0000000001000001"),equalTo("A"));
|
||||
assertThat(binDecode("0000000011000001"),equalTo("Á"));
|
||||
assertThat(binDecode("00000000010000010000000001000001"),equalTo("AA"));
|
||||
assertThat(binDecode("0110111100100010"), equalTo("漢"));
|
||||
assertThat(binDecode("0000000001000001"), equalTo("A"));
|
||||
assertThat(binDecode("0000000011000001"), equalTo("Á"));
|
||||
assertThat(binDecode("00000000010000010000000001000001"), equalTo("AA"));
|
||||
}
|
||||
|
||||
@Test
|
||||
public void binEncode_shouldEncodeAStringToBinaryFormat() throws Exception {
|
||||
assertThat(binEncode("漢"), equalTo("0110111100100010"));
|
||||
assertThat(binEncode("A"), equalTo("0000000001000001"));
|
||||
assertThat(binEncode("Á"), equalTo("0000000011000001"));
|
||||
assertThat(binEncode("AA"), equalTo("00000000010000010000000001000001"));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user