如何将一字符串动态赋值成16进制值,内含详细代码(总共几行)
MDK环境下,有如下实现
uint8_t Settimebuf[7];
Settimebuf[6] = 0x12; //年
Settimebuf[5] = 0x07; //周
Settimebuf[4] = 0x06; //月
Settimebuf[3] = 0x17; //日
Settimebuf[2] = 0x10; //时
Settimebuf[1] = 0x23; //分
Settimebuf[0] = 0x20;//秒
Set1381Time(Settimebuf);
现有一个char变量动态记录了年月日时分秒的信息"120617102320",请教如何将字符串中相应时间信息赋值成如上,以实现可动态设置时间信息
谢谢,一个非C程序员
[解决办法]
不知道你为什么要用16进制,如果一定要用的话,那你就改一处代码即可,把×10 改成×16
#include <stdio.h>#define GET_NUM(ch) ((ch) - '0')unsigned char* set_buf(const char* str, unsigned char* buf, const size_t LEN) { size_t i; unsigned char num = 0; for (i = 0; i < LEN; ++i) { num = GET_NUM(str[2*i]) * 10 + GET_NUM(str[2*i+1]); buf[i] = num; } return buf;}/* 测试代码 */int main() { const char *str = "120617102320"; size_t i; unsigned char buf[7]; const size_t LEN = sizeof(buf); set_buf(str, buf, 7); for (i = 0; i < LEN; ++i) { printf("%d\n", buf[i]); } return 0;}
[解决办法]
[User:root Time:21:23:37 Path:/home/liangdong/c]$ makegcc -g -I./include -c -o src/main.o src/main.cgcc -o output src/main.o -lpthread -lm -lzMakefile done.[User:root Time:21:23:37 Path:/home/liangdong/c]$ ./output 0x12 0x7 0x6 0x17 0x10 0x23 0x20 [User:root Time:21:23:38 Path:/home/liangdong/c]$ cat src/main.c #include <stdio.h>#include <stdlib.h>#include <string.h>#include <stdint.h>int strpuint8(const char *time, uint8_t *buf) { if (!time) { return -1; } int i; for (i = 0; i != 7; ++ i) { if (sscanf(time + i * 2, "%2x", buf + i) != 1) { return -1; } } return 0;}int main(int argc, char* const argv[]) { uint8_t set_time_buf[7]; const char *time = "12070617102320"; int ret = strpuint8(time, set_time_buf); if (ret == 0) { int i; for (i = 0; i != 7; ++ i) { printf("0x%x ", set_time_buf[i]); } } printf("\n"); return 0;}