如何将一字符串动态赋值成16进制值,内含详细代码(总共几行)

chenchen_2011 2012-06-19 12:44:01
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程序员
...全文
180 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
qq120848369 2012-06-19
  • 打赏
  • 举报
回复
[User:root Time:21:23:37 Path:/home/liangdong/c]$ make
gcc -g -I./include -c -o src/main.o src/main.c
gcc -o output src/main.o -lpthread -lm -lz
Makefile 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;
}
jiuchang 2012-06-19
  • 打赏
  • 举报
回复
基本上如1楼所说,就是每两个字节转换为一个16进制数,高位乘以10或16再加上低位就可以了,10进制或16进制都很容易的
turing-complete 2012-06-19
  • 打赏
  • 举报
回复
不知道你为什么要用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;
}

69,373

社区成员

发帖
与我相关
我的任务
社区描述
C语言相关问题讨论
社区管理员
  • C语言
  • 花神庙码农
  • 架构师李肯
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧