c# - 将 int 转换为 BCD 字节数组

标签 c# .net encryption bcd

我想使用 BCD 将 int 转换为 byte[2] 数组。

有问题的 int 将来自代表年份的 DateTime 并且必须转换为两个字节。

是否有任何预制函数可以执行此操作,或者您能给我一个执行此操作的简单方法吗?

示例:

int year = 2010

会输出:

byte[2]{0x20, 0x10};

最佳答案

    static byte[] Year2Bcd(int year) {
        if (year < 0 || year > 9999) throw new ArgumentException();
        int bcd = 0;
        for (int digit = 0; digit < 4; ++digit) {
            int nibble = year % 10;
            bcd |= nibble << (digit * 4);
            year /= 10;
        }
        return new byte[] { (byte)((bcd >> 8) & 0xff), (byte)(bcd & 0xff) };
    }

请注意,您要求的是大端结果,这有点不寻常。

关于c# - 将 int 转换为 BCD 字节数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7107026/

相关文章:

c# - "Security"和 ASP.NET 路由引擎的问题

sql-server - 将 c# 模型类参数调用限制为不存在的表字段的 MS SQL 服务器

c# - 数字角色 SDK : Transfer EnrollmentForm image to another form

c# - HttpWebRequest 内容长度错误

c# - XtraGrid 中列中的唯一值列表

c# - Caliburn Micro Action

c# - 在 TFS 中取消 "get latest version"是否有效?

.net - 为特定密码启用 TLS 1.2

Java/PHP 加密 CAST-256

linux - 检查是否为 SSH 配置了 RSA