Last active
September 25, 2018 14:48
-
-
Save lovasoa/00542e498f99e79b59dbae50b1f4b417 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
import java.io.*; | |
import java.nio.charset.Charset; | |
public class Main { | |
public static byte[] to1251Bytes(final String str) { | |
try { | |
final ByteArrayOutputStream os = new ByteArrayOutputStream(str.length()); | |
final Writer out = new BufferedWriter(new OutputStreamWriter(os, Charset.forName("Cp1251"))); | |
out.write(str); | |
out.flush(); | |
return os.toByteArray(); | |
} catch (IOException ex) { | |
return null; | |
} | |
} | |
public static void main(String[] args) { | |
to1251Bytes("hello"); | |
} | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.company; | |
import static com.company.Main.to1251Bytes; | |
import static org.junit.Assert.assertArrayEquals; | |
public class MainTest { | |
@org.junit.Test | |
public void testTo1251Bytes() { | |
assertArrayEquals( | |
new byte[]{97, 97, 97}, | |
to1251Bytes("aaa") | |
); | |
} | |
@org.junit.Test | |
public void testCyrillics() { | |
// See https://ru.wikipedia.org/wiki/Windows-1251 | |
// -23 = (byte) 0xE9 | |
assertArrayEquals( | |
new byte[]{-23, -23, -23}, | |
to1251Bytes("ййй") | |
); | |
} | |
@org.junit.Test | |
public void testNonEncodable() { | |
// 63 is the ascii code for '?' | |
assertArrayEquals( | |
new byte[]{63, 63, 63}, | |
to1251Bytes("ééé") | |
); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment