【问题标题】:Conversion char* string to hex uint16 [closed]将 char* 字符串转换为十六进制 uint16 [关闭]
【发布时间】:2017-12-01 13:39:19
【问题描述】:

我需要构建一个函数,我的输入是一个 char *string,我需要在 uint16 中获得“相同的表示”。

例如:

input: "12"  -->  output: 0x0012
input: "0"   -->  output: 0x0000
input "123"  -->  output: 0x0123
input "1234" -->  output: 0x1234

PD:我不能使用strtol、sscanf等“官方函数”...

【问题讨论】:

  • 然后考虑编写您的函数,如果您对此有任何疑问,请回来。
  • 你忘了问问题,顺便说一句。

标签: c string hex converter strtol


【解决方案1】:

这个怎么样?

#include <stdio.h>
#include <stdint.h>

unsigned int
trans(unsigned char c){
  if ('0' <=c && c <= '9') return c - '0';
  if ('A' <=c && c <= 'F') return c - 'A' + 0x0A;
  if ('a' <=c && c <= 'f') return c - 'a' + 0x0A;
  return 0;
}

uint16_t
hex_to_uint16(const char* s) {
  uint16_t v = 0;
  while (*s)
    v = (v << 4) + trans(*s++);
  return v;
}

#include <assert.h>

int
main(int argc, char* argv[]) {
  assert(0x0012 == hex_to_uint16("12"));
  assert(0x0000 == hex_to_uint16("0"));
  assert(0x0123 == hex_to_uint16("123"));
  assert(0x1234 == hex_to_uint16("1234"));
  assert(0xffff == hex_to_uint16("ffff"));
  return 0;
}

【讨论】:

  • 1) (char*)char *p = (char*) s; 中是一个弱实践。使用const char *p = s; 2) if (p &gt; s)if (p &gt; s) v = v &lt;&lt; 4; 中不需要
猜你喜欢
  • 1970-01-01
  • 2020-07-18
  • 2013-03-20
  • 2013-05-29
  • 1970-01-01
相关资源
最近更新 更多