什麼是BCD 碼

來源:互聯網
上載者:User
 

BCD碼(Binary-Coded Decimal)亦稱二進碼十進數或二-十進位代碼。用4位位元來表示1位十進位數中的0~9這10個數位。是一種二進位的數字編碼形式,用二進位編碼的十進位代 碼。BCD碼這種編碼形式利用了四個位元來儲存一個十進位的數位,使二進位和十進位之間的轉換得以快捷的進行。這種編碼技巧最常用於會計系統的設計裡,因 為會計制度經常需要對很長的數字串作準確的計算。相對於一般的浮點式記數法,採用BCD碼,既可儲存數值的精確度,又可免卻使電腦作浮點運算時所耗費的時 間。此外,對於其他需要高精確度的計算,BCD編碼亦很常用。

來源:http://baike.baidu.com/view/45179.htm

 

BCD 編碼解碼函數如下:

/// <summary>/// BCD解碼/// </summary>/// <param name="b"></param>/// <returns></returns>public static byte UnpackBCD(byte b){    //高四位    byte b1 = (byte)(b >> 4);    //低四位    byte b2 = (byte)(b & 0x0F);    return (byte)(b1 * 10 + b2);}/// <summary>/// BCD編碼/// </summary>/// <param name="b"></param>/// <returns></returns>public static byte PackBCD(byte b){    //高四位    byte b1 = (byte)(b / 10);    //低四位    byte b2 = (byte)(b % 10);    return (byte)((b1<<4)|b2);}

 

BCD 編碼測試,代碼如下:

class Program{    // BCD編碼    public static byte PackBCD(byte b)    {        //高四位        byte b1 = (byte)(b / 10);        //低四位        byte b2 = (byte)(b % 10);        return (byte)((b1 << 4) | b2);    }    static void Main(string[] args)    {        byte[] buff = new byte[2];        DateTime date = DateTime.Now;        byte in_Month = (byte)(date.Month);        byte in_Day = (byte)(date.Day);        Console.WriteLine(in_Month.ToString() +"  "+ in_Day.ToString());        buff[0] = PackBCD(in_Month);        buff[1] = PackBCD(in_Day);        Console.WriteLine(buff[0].ToString() + "  " + buff[1].ToString());        Console.ReadKey();    }}

結果如下:

可以看出,月份4進行BCD編碼後沒有改變,23日進行BCD編碼後變成了35。

 

BCD 解碼測試,代碼如下:

class Program{    // BCD解碼    public static byte UnpackBCD(byte b)    {        //高四位        byte b1 = (byte)(b >> 4);        //低四位        byte b2 = (byte)(b & 0x0F);        return (byte)(b1 * 10 + b2);    }    static void Main(string[] args)    {        byte[] buff = new byte[2] { 0x04, 0x23 };        Console.WriteLine(buff[0].ToString() + "  " + buff[1].ToString());        byte in_Month = UnpackBCD(buff[0]);        byte in_Day = UnpackBCD(buff[1]);        Console.WriteLine(in_Month.ToString() + "  " + in_Day.ToString());        Console.ReadKey();    }}

結果如下:

可以看出,月份4進行BCD解碼後沒有改變,35進行BCD解碼後還原成了23日。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.