0

我有应该存储在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

4 回答 4

2
arr[0] = strtol(str,NULL,16);  // If one entry is big enough to hold it.
于 2013-08-15T19:44:30.217 回答
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;
}
于 2013-08-15T20:51:41.570 回答
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。

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

于 2013-08-15T19:44:12.037 回答
0

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

"解析 C 字符串 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;
}
于 2013-08-15T19:48:54.747 回答