如何将十进制数字数组更改为十六进制?

时间:2018-11-10 13:53:58

标签: c

到目前为止,我正在尝试将这些十进制数字转换为十六进制数字,然后使用fwrite()函数将其写入文件。有人可以帮忙吗?

struct tm* tm_info;
char day[2];
char month[2];
char year[4];
char hour[2];
char min[2];
char sec [2];
char weekday[2];
time(&timer);
tm_info = localtime(&timer);
unsigned short ab= strftime(day, 2, "%d", tm_info);
unsigned short bc= strftime(month, 2, "%m", tm_info);
unsigned short cd= strftime(year, 4, "%Y", tm_info);
unsigned short de= strftime(hour, 2, "%H", tm_info);
unsigned short ef= strftime(min, 2, "%M", tm_info);
unsigned short gh= strftime(sec, 2, "%S", tm_info);

1 个答案:

答案 0 :(得分:0)

  

将这些十进制数字转换为十六进制数字,然后使用fwrite()函数将其写入文件。

获取时间信息

time(&timer);
struct tm* tm_info = localtime(&timer);

让我们尝试在1个月的时间内解决此问题-

// Do not hard code 2, use the size of the array
// size_t strftime(char *s, size_t maxsize, const char *format, const struct tm *timeptr)
//   forms a _string_ at s.  Make the buffer large enough for a conversion of any `int`.
//   No reason to be stingy here. 
//   Let us assume a worst case of a 64-bit int which needs 21 char printed as a string.
// strftime() returns 
//   "total number of resulting characters including the terminating null character"
//    or zero on error.  Useful for error checking.
// unsigned short bc= strftime(month, 2, "%m", tm_info);
char ibuffer[21];
if (strftime(ibuffer, sizeof ibuffer, "%m", tm_info) > 0) {
  // Success

字符串 ibuffer转换为unsigned

  unsigned value = atoi(ibuffer);

value作为文本写入month。用领先的'0'填充,并确保代码在month[]内。

  char month[2];
  snprintf(month, sizeof month, "%02X", value);

写入文件

  fwrite(month, sizeof month, 1, out_stream);

无需通过strftime()。只需阅读,甚至可以抵消各种struct tm成员。

  char month[2];
  snprintf(month, sizeof month, "%02X", tm_info->tm_mon + 1u);
  fwrite(month, sizeof month, 1, out_stream);