转换一个INT到BCD字节数组 [英] Converting a int to a BCD byte array

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

问题描述

我想一个int转换为字节[2]数组采用BCD。

在讨论的INT将来自日期时间再presenting年,并必须转换为两个字节。

有没有pre制功能,这是否也可以给我这样的一个简单的方法?

例如:

  INT年= 2010
 

将输出:

 字节[2] {为0x20,0x10的};
 

解决方案

 静态的byte [] Year2Bcd(INT年){
        如果(年℃,||一年> 9999)抛出新的ArgumentException();
        INT BCD = 0;
        对(INT位= 0;位4; ++位){
            INT半字节=一年10%;
            BCD | =四位<< (数字* 4);
            年/ = 10;
        }
        返回新的字节[] {(字节)((BCD>> 8)及0xFF的),(字节)(BCD&安培; 0xFF的)};
    }
 

要注意的是,你问一个大端的结果,这是一个有点不寻常。

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

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?

example:

int year = 2010

would output:

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天全站免登陆