将 int 转换为 BCD 字节数组 [英] Converting a int to a BCD byte array

查看:94
本文介绍了将 int 转换为 BCD 字节数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to convert an int to a byte[2] array using BCD.

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

The int in question will come from DateTime representing the Year and must be converted to two bytes.

是否有任何预制函数可以做到这一点,或者您能给我一个简单的方法吗?

Is there any pre-made function that does this or can you give me a simple way of doing this?

示例:

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) };
    }

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

Beware that you asked for a big-endian result, that's a bit unusual.

这篇关于将 int 转换为 BCD 字节数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆