如何在c#上将DateTime(yyyyMMddhhmm)转换为压缩的bcd (大小为6)表示?
using System;
namespace Exercise
{
internal class Program
{
private static void Main(string[] args)
{
byte res = to_bcd(12);
}
private static byte to_bcd(int n)
{
// extract each digit from the input number n
byte d1 = Convert.ToByte(n/10);
byte d2 = Convert.ToByte(n%10);
// combine the decimal digits into a BCD number
return Convert.ToByte((d1 << 4) | d2);
}
}
}
在res变量上得到的结果是18。
谢谢!
发布于 2012-02-26 02:32:51
当你传递给to_bcd时,你得到的是正确的18==12(十六进制)。
static byte[] ToBCD(DateTime d)
{
List<byte> bytes = new List<byte>();
string s = d.ToString("yyyyMMddHHmm");
for (int i = 0; i < s.Length; i+=2 )
{
bytes.Add((byte)((s[i] - '0') << 4 | (s[i+1] - '0')));
}
return bytes.ToArray();
}
发布于 2012-02-26 02:03:09
我将举一个简短的例子来演示这个想法。您可以将此解决方案扩展到整个日期格式输入。
BCD格式将两个十进制数恰好封装为一个8位数字。例如,92
的二进制表示形式为:
1001 0010
或者十六进制的0x92
。当转换为decimal时,它恰好是146
。
这样做的代码需要将第一个数字左移4位,然后与第二个数字组合。所以:
byte to_bcd(int n)
{
// extract each digit from the input number n
byte d1 = n / 10;
byte d2 = n % 10;
// combine the decimal digits into a BCD number
return (d1 << 4) | d2;
}
https://stackoverflow.com/questions/9446497
复制相似问题