Skip to content

Instantly share code, notes, and snippets.

@doggy8088
Created November 30, 2021 18:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save doggy8088/ac443582b41ea3e4d4b063f6cf9ddae4 to your computer and use it in GitHub Desktop.
Save doggy8088/ac443582b41ea3e4d4b063f6cf9ddae4 to your computer and use it in GitHub Desktop.
var startSymbol = "Ë";
var encodedData = "177345239061003";
var checkSymbol = "";
var stopSymbol = "Î";
// 預設使用 Code Set A ( 128A ) 字元集
Code128Type type = Code128Type.CodeSetA;
// 如果有小寫字元就改用 Code Set B ( 128B ) 字元集
if (Regex.IsMatch(encodedData, "[a-z]"))
{
type = Code128Type.CodeSetB;
}
var checksum = 0;
switch (type)
{
case Code128Type.CodeSetA:
startSymbol = "Ë";
checksum = 103;
break;
case Code128Type.CodeSetB:
startSymbol = "Ì";
checksum = 104;
break;
case Code128Type.CodeSetC:
startSymbol = "Í";
checksum = 105;
break;
default:
throw new ArgumentException("錯誤的 Code128Type 類型", "type");
}
var chars = encodedData.ToCharArray();
for (int i = 0; i < chars.Length; i++)
{
var position = i + 1;
var value = 0;
var asciiasc = (int)chars[i];
if (asciiasc >= 32)
{
value = asciiasc - 32;
checksum += value * position;
}
else
{
value = asciiasc + 64;
checksum += value * position;
}
//$"Value: {value}".Dump();
//$"Checksum: {checksum}".Dump();
}
checksum = checksum % 103;
//checksum.Dump();
if (checksum < 95)
{
checkSymbol = char.ConvertFromUtf32(checksum + 32);
}
else
{
checkSymbol = char.ConvertFromUtf32(checksum + 100);
}
var result = startSymbol + encodedData + checkSymbol + stopSymbol;
result.Dump();
public enum Code128Type
{
CodeSetA,
CodeSetB,
CodeSetC
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment