#include "stdafx.h"
#include <stdio.h>
#include <time.h>
#include <malloc.h>
/* 獲取系統時間 */
void get_sys_time(int *year, int *mon, int *day, int *hour, int *min, int *sec, int *wday)
{
struct tm *timeinfo;
time_t now;
time(&now);
timeinfo = localtime(&now);
*year = timeinfo->tm_year + 1900;
*mon = timeinfo->tm_mon + 1;
*day = timeinfo->tm_mday;
*hour = timeinfo->tm_hour;
*min = timeinfo->tm_min;
*sec = timeinfo->tm_sec;
*wday = timeinfo->tm_wday;
}
/* 將十進制數轉換成16進制數 */
void dec2hex(int input, unsigned char *output)
{
int in_tmp = 0;
in_tmp = input / 10;
in_tmp <<= 4;
in_tmp |= input % 10;
memcpy(output, &in_tmp, 1);
}
/* 將當前的系統時間轉換為bcd格式 */
void time_bcd(unsigned char *timebcd)
{
int year, mon, day, hour, min, sec, wday;
unsigned char *tmp = (unsigned char *)malloc(1 * sizeof(unsigned char));
get_sys_time(&year, &mon, &day, &hour, &min, &sec, &wday);
dec2hex(year / 100, tmp);
memcpy(timebcd, tmp, 1);
dec2hex(year % 100, tmp);
memcpy(timebcd + 1, tmp, 1);
dec2hex(mon, tmp);
memcpy(timebcd + 2, tmp, 2);
dec2hex(day, tmp);
memcpy(timebcd + 3, tmp, 3);
dec2hex(hour, tmp);
memcpy(timebcd + 4, tmp, 4);
dec2hex(min, tmp);
memcpy(timebcd + 5, tmp, 5);
dec2hex(sec, tmp);
memcpy(timebcd + 6, tmp, 6);
dec2hex(wday, tmp);
memcpy(timebcd + 7, tmp, 7);
free(tmp);
}
/* 輸出指定內存地址空間的16進制值 */
void my_print(unsigned char *buf, int len)
{
int i = 0;
while (i<len)
{
printf("%02x", buf[i]);
i++;
}
printf("\n");
}
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
unsigned char ttmp[16];
time_bcd(ttmp);
my_print(ttmp, 8);
system("PAUSE");
return 0;
}
關於BCD、ASCII和BINARAY儲存示例:2015
BCD:0x20 0x15
BINARY:0x14 0x0f
ACSII:0x320x300x310x35
2的ASCII碼為十六進制數32,十進制數50。
部分數字的ASCII碼如下:
數字0的ASCII碼為十六進制數30,十進制數48
數字1的ASCII碼為十六進制數31,十進制數49
數字2的ASCII碼為十六進制數32,十進制數50
數字3的ASCII碼為十六進制數33,十進制數51
數字4的ASCII碼為十六進制數34,十進制數52
數字5的ASCII碼為十六進制數35,十進制數53
數字6的ASCII碼為十六進制數36,十進制數54
數字7的ASCII碼為十六進制數37,十進制數55
數字8的ASCII碼為十六進制數38,十進制數56
數字9的ASCII碼為十六進制數39,十進制數57
ASCII(American Standard Code for Information Interchange,美國標准信息交換代碼)是基於拉丁字母的一套電腦編碼系統,主要用於顯示現代英語和其他西歐語言。它是現今最通用的單字節編碼系統,並等同於國際標准ISO/IEC 646。
