2012-02-25 74 views
2

如何將DateTime(yyyyMMddhhmm)轉換爲c#上的壓縮bcd(大小6)表示形式?DateTime到BCD表示

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

你對資源變量的結果是18

謝謝!

回答

1

我將舉一個簡短的例子來展示這個想法。您可以將此解決方案擴展到整個日期格式輸入。

BCD格式將正好兩個十進制數字封裝爲一個8位數字。例如,92表示將是,在二進制:

1001 0010 
十六進制

0x92。轉換爲十進制時,這恰好是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; 
} 
+0

您好格雷格和感謝您的快速反應,但我沒有真正明白。 我按照你的建議int = 12(第一條消息的完整示例): 你在res變量上得到的結果是18. 我期望在這裏有1字節的表示。 另外,長DateTime(yyyyMMddhhmm)應該做什麼?我應該將其轉換爲int64表示形式並將其拆分爲大小爲2的6個整數? 謝謝! – 2012-02-25 18:27:15

+0

您的計算是正確的。十進制數字「18」是十六進制的「0x12」,也是「12」十進制的BCD表示。 – 2012-02-25 18:43:03

2

當你傳遞給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(); 
} 
+0

非常感謝!作品! – 2012-02-25 18:36:38

+0

@TzvikaPika,當我們喜歡答案時,我們在做什麼? – 2012-02-25 18:53:38