如何将文字字符十六进制值转换为十六进制值本身?

时间:2013-08-15 19:34:22

标签: c string hex

我的文字值应该存储在unsigned char[64]数组中。如何将这些值转换为十六进制等效值?

int main() {

    unsigned char arry[1] = { 0xaa }

    char* str = "fe"; //I want to store 0xfe on arry[0]

    arry[0] = 0xfe; // this works, but I have to type it
    arry[0] = 0x + str; //obviously fails

    return 0;
}

任何指针?

4 个答案:

答案 0 :(得分:2)

arr[0] = strtol(str,NULL,16);  // If one entry is big enough to hold it.

答案 1 :(得分:0)

对于每个字符c,值为:

 if ('0' <= c && c <= '9') return c - '0';
 if ('a' <= c && c <= 'f') return c - 'a' + 10;
 if ('A' <= c && c <= 'F') return c - 'A' + 10;

 // else error, invalid digit character

现在只需从左到右遍历字符串,将数字值相加,然后每次将结果乘以16。

(这是由基数为16的strto*l函数中的标准库实现的。)

答案 2 :(得分:0)

使用函数strtol()将字符串转换为特定基数中的long:http://www.cplusplus.com/reference/cstdlib/strtol/

“解析C-string str将其内容解释为指定基数的整数,并以long int值的形式返回。如果endptr不是空指针,则该函数还设置endptr的值指向数字后面的第一个字符。“

示例:

#include <stdio.h>      /* printf */
#include <stdlib.h>     /* strtol */

int main ()
{
  char szNumbers[] = "2001 60c0c0 -1101110100110100100000 0x6fffff";
  char * pEnd;
  long int li1, li2, li3, li4;
  li1 = strtol (szNumbers,&pEnd,10);
  li2 = strtol (pEnd,&pEnd,16);
  li3 = strtol (pEnd,&pEnd,2);
  li4 = strtol (pEnd,NULL,0);
  printf ("The decimal equivalents are: %ld, %ld, %ld and %ld.\n", li1, li2, li3, li4);
  return 0;
}

答案 3 :(得分:0)

将任意长度的解决方案放在一起 可悲的是,字符串到X是冗长的:讨厌处理非十六进制字符串,奇数长度,太大等等。

#include <string.h>
#include <stdio.h>

// S assumed to be long enough.
// X is little endian
void BigXToString(const unsigned char *X, size_t Length, char *S) {
  size_t i;
  for (i = Length; i-- > 0; ) {
    sprintf(S, "%02X", X[i]);
    S += 2;
  }
}

int BigStringToX(const char *S, unsigned char X[], size_t Length) {
  size_t i;
  size_t ls = strlen(S);
  if (ls > (Length * 2)) {
    return 1;  //fail, too big
  }
  int flag = ls & 1;
  size_t Unused = Length - (ls/2) - flag;
  memset(&X[Length - Unused], 0, Unused);  // 0 fill unused
  char little[3];
  little[2] = '\0';
  for (i = Length - Unused; i-- > 0;) {
    little[0] = *S++;
    little[1] = flag ? '\0' : *S++;
    flag = 0;
    char *endptr;
    X[i] = (unsigned char) strtol(little, &endptr, 16);
    if (*endptr) return 1;   // non-hex found
    if (*S == '\0') break;
  }
  return 0;
}

int main() {
  unsigned char X[64];
  char S[64 * 2 + 2];
  char T[64 * 2 + 2];
  strcpy(S, "12345");
  BigStringToX(S, X, sizeof(X));
  BigXToString(X, sizeof(X), T);
  printf("'%s'\n", T);
  return 0;
}