原文https://blog.csdn.net/MengJun1/article/details/100082320
大华条码称同步商品时,商品名需要转化为区位码才可以成功显示,简单记录一下转化方式,目前存在的缺陷是有的特殊字符不能正确识别。
/**
* 获取完整的区位码
*
* @param name 原始字符串
* @return 区位码
*/
private String getTotalAreaCode(String name) {
StringBuilder stringBuilder = new StringBuilder();
char[] nameChar = name.toCharArray();
for (char c : nameChar) {
if (isChinese(c))
stringBuilder.append(toAreaCode(String.valueOf(c), true));
else
stringBuilder.append(toAreaCode(String.valueOf(c), false));
}
String code = stringBuilder.toString();
if (code.contains("-")){
Log.e(TAG,name + "的区位码存在非法字符:" + code);
return "";
}else {
Log.d(TAG, name + "的区位码:" + code);
return code;
}
}
/**
* 按照是否是中文字符分类获取区位码
*
* @param word 原始值
* @param isChina 是否是中文字符
* @return 区位码
*/
private String toAreaCode(String word, boolean isChina) {
StringBuilder areaCode = new StringBuilder();
byte[] bs;
try {
bs = word.getBytes("GB2312");
for (byte b : bs) {
int code = Integer.parseInt(Integer.toHexString(b & 0xFF), 16);
if (isChina) {
int temp = code - 0x80 - 0x20;
if (temp < 10) {
areaCode.append("0").append(temp);
} else {
areaCode.append(temp);
}
} else {
int temp = code - 32;
if (temp < 10) {
areaCode.append("030").append(temp);
} else {
areaCode.append("03").append(temp);
}
}
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
Log.e(TAG, "区位码转码异常,可能导致乱码或者空白字符");
}
return areaCode.toString();
}
/**
* 根据Unicode编码判断中文汉字和符号
*/
private static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
return ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_B
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION;
}
————————————————
版权声明:本文为CSDN博主「梦君DS」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/MengJun1/article/details/100082320