Created
February 12, 2019 11:27
-
-
Save ccentauri/8f4348486b80c727007be4061489ee32 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
public class Code128WriterPreprocessor { | |
private static final char ESCAPE_FNC_1 = '\u00f1'; | |
private static final char ESCAPE_FNC_2 = '\u00f2'; | |
private static final char ESCAPE_FNC_3 = '\u00f3'; | |
private static final char ESCAPE_FNC_4 = '\u00f4'; | |
private static final String ENCODING_LATIN_1 = "latin1"; | |
public static String process(String data) { | |
Byte[] dataBytes; | |
try { | |
dataBytes = convertBytesFromPrimitive(data.getBytes(ENCODING_LATIN_1)); | |
} catch (UnsupportedEncodingException e) { | |
Timber.e("Can't read bytes from data", e); | |
return data; | |
} | |
for (int i = 0; i < dataBytes.length; i++) { | |
if (dataBytes[0] == (byte) ESCAPE_FNC_1 || dataBytes[0] == (byte) ESCAPE_FNC_2 || | |
dataBytes[0] == (byte) ESCAPE_FNC_3 || dataBytes[0] == (byte) ESCAPE_FNC_4) { | |
continue; | |
} | |
if (dataBytes[i] < 0) { // Byte is out of range | |
dataBytes[i] = (byte) (dataBytes[i] + 128); // Set in range | |
dataBytes = addEscapeFunc4OnPosition(dataBytes, i); // Add escape char | |
} | |
} | |
try { | |
return new String(convertBytesToPrimitive(dataBytes), ENCODING_LATIN_1); | |
} catch (UnsupportedEncodingException e) { | |
Timber.e("Encoding error", e); | |
return data; | |
} | |
} | |
private static Byte[] convertBytesFromPrimitive(byte[] data) { | |
Byte[] byteArray = new Byte[data.length]; | |
for (int i = 0; i < byteArray.length; i++) { | |
byteArray[i] = data[i]; | |
} | |
return byteArray; | |
} | |
private static byte[] convertBytesToPrimitive(Byte[] data) { | |
byte[] byteArray = new byte[data.length]; | |
for (int i = 0; i < byteArray.length; i++) { | |
byteArray[i] = data[i]; | |
} | |
return byteArray; | |
} | |
private static Byte[] addEscapeFunc4OnPosition(Byte[] data, int position) { | |
Byte[] result = new Byte[data.length]; | |
List<Byte> list = new ArrayList<>(Arrays.asList(data)); | |
list.add(position, (byte) ESCAPE_FNC_4); | |
return list.toArray(result); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment