0

我想将一个16 字节的ascii字符串转换为 16 字节的十六进制整数。请帮忙。这是我的代码:

uint stringToByteArray(char *str,uint **array)
{

    uint i, len=strlen(str) >> 1;

    *array=(uint *)malloc(len*sizeof(uint));

    //Conversion of str (string) into *array (hexadecimal)

    return len;

}
4

2 回答 2

1

如果您正在寻找以十六进制形式打印整数,这可能会有所帮助:

#include <stdio.h>

int main() {
    /* define ASCII string */
    /* note that char is an integer number type */
    char s[] = "Hello World";
    /* iterate buffer */
    char *p;
    for (p = s; p != s+sizeof(s); p++) {
        /* print each integer in its hex representation */
        printf("%02X", (unsigned char)(*p));
    }
    printf("\n");
    return 0;
}

如果您只想将char数组转换为 1 字节整数数组,那么您已经完成了。char已经是整数类型。您可以使用已有的缓冲区,或使用malloc/memcpy将数据复制到新的缓冲区。

您可能想查看 中定义的显式宽度整数类型stdint.h,例如,uint8_t对于单字节无符号整数。

于 2013-06-23T17:59:53.770 回答
0

16 个字符长度的C-“字符串”是 16字节!

要将其转换为“字节”数组(长度为 16 个条目),您可能需要执行以下操作:

#include <unistd.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>

/* Copies all characters of str into a freshly allocated array pointed to by *parray. */
/* Returns the number of characters bytes copied and -1 on error. Sets errno accordingly. */ 
size_t stringToByteArray(const char * str, uint8_t **parray)
{
  if (NULL == str)
  {
    errno = EINVAL;
    return -1;
  }

  {
    size_t size = strlen(str);

    *parray = malloc(size * sizeof(**parray));
    if (NULL == *parray)
    {
      errno = ENOMEM;
      return -size;
    }

    for (size_t s = 0; s < size; ++s)
    {
      (*parray)[s] = str[s];
    }

    return size;
  }
}

int main()
{
  char str[] = "this is 16 bytes";

  uint8_t * array = NULL;
  ssize_t size = stringToByteArray(str, &array);
  if (-1 == size)
  {
    perror("stringToByteArray() failed");
    return EXIT_FAILURE;
  }

  /* Do what you like with array. */

  free(array);

  return EXIT_SUCCESS;
}
于 2013-06-23T19:11:14.570 回答