Skip to content

Instantly share code, notes, and snippets.

@lovasoa
Last active September 25, 2018 14:48
Show Gist options
  • Save lovasoa/00542e498f99e79b59dbae50b1f4b417 to your computer and use it in GitHub Desktop.
Save lovasoa/00542e498f99e79b59dbae50b1f4b417 to your computer and use it in GitHub Desktop.
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");
}
}
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