Skip to content

Instantly share code, notes, and snippets.

@cab404
Last active December 15, 2016 02:07
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save cab404/96b1cba0eec6e17886232ff493005517 to your computer and use it in GitHub Desktop.
/**
* Generates EAN13 barcode data
*
* @author cab404
*/
public class EAN13 {
public static final int[] INDENTS = {0, 2, 44, 46, 92, 94};
public static final int LENGTH = 95;
private final static byte[][] CODEMAP =
{
{13, 25, 19, 61, 35, 49, 47, 59, 55, 11},
{39, 51, 27, 33, 29, 57, 5, 17, 9, 23},
{114, 102, 108, 66, 92, 78, 80, 68, 72, 116}
};
private final static byte FILLMAP[] = {
0, 52, 44, 28, 50, 38, 14, 42, 26, 22
};
private final static byte PADDING = 5;
private final static byte DIV = 10;
byte[] data = new byte[13];
public String form(String from) {
if (from.length() != 13)
throw new NumberFormatException();
for (int i = 0; i < from.length(); i++)
if (!Character.isDigit(from.charAt(i)))
throw new NumberFormatException();
else
data[i] = (byte) (from.charAt(i) - '0');
StringBuilder builder = new StringBuilder();
byte head = data[0];
decode(PADDING, 3, builder);
for (int i = 1; i < 7; i++)
decode(CODEMAP[(FILLMAP[head] & (1 << i - 1)) >> i - 1][data[i]], 7, builder);
decode(DIV, 5, builder);
for (int i = 7; i < 13; i++)
decode(CODEMAP[2][data[i]], 7, builder);
decode(PADDING, 3, builder);
return builder.toString();
}
private char[] decoded = new char[8];
private void decode(byte code, int len, StringBuilder to) {
int offset = 1;
int last = 7;
for (int i = 7; i >= 0; i--) {
decoded[i] = (code & offset) > 0 ? '1' : '0';
last = decoded[i] == '1' ? i : last;
offset <<= 1;
}
to.append(decoded, 8 - len, len);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment