Skip to content

Commit 3924c52

Browse files
authored
Merge pull request Blankj#690 from BigAdam2005/addBinaryEncoding
Added binary encoding
2 parents bd942f3 + d53d469 commit 3924c52

File tree

2 files changed

+36
-0
lines changed

2 files changed

+36
-0
lines changed

utilcode/src/main/java/com/blankj/utilcode/util/EncodeUtils.java

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -183,4 +183,34 @@ public static CharSequence htmlDecode(final String input) {
183183
return Html.fromHtml(input);
184184
}
185185
}
186+
187+
/**
188+
* Return the binary encoded string padded with one space
189+
*
190+
* @param input
191+
* @return binary string
192+
*/
193+
public static String binEncode(final String input) {
194+
StringBuilder stringBuilder = new StringBuilder();
195+
for (char i : input.toCharArray()) {
196+
stringBuilder.append(Integer.toBinaryString(i));
197+
stringBuilder.append(' ');
198+
}
199+
return stringBuilder.toString();
200+
}
201+
202+
/**
203+
* Return UTF-8 String from binary
204+
*
205+
* @param input binary string
206+
* @return UTF-8 String
207+
*/
208+
public static String binDecode(final String input){
209+
String[] splitted = input.split(" ");
210+
StringBuilder sb = new StringBuilder();
211+
for(String i : splitted){
212+
sb.append(((char) Integer.parseInt(i.replace(" ", ""), 2)));
213+
}
214+
return sb.toString();
215+
}
186216
}

utilcode/src/test/java/com/blankj/utilcode/util/EncodeUtilsTest.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -70,4 +70,10 @@ public void htmlEncode_htmlDecode() {
7070

7171
assertEquals(html, EncodeUtils.htmlDecode(encodeHtml).toString());
7272
}
73+
@Test
74+
public void binEncode_binDecode(){
75+
String test = "test";
76+
String binary = EncodeUtils.binEncode(test);
77+
assertEquals("test", EncodeUtils.binDecode(binary));
78+
}
7379
}

0 commit comments

Comments
 (0)