user2503061
user2503061

Reputation: 11

ASCII string to hexadecimal integers conversion

I want to convert an ascii string of 16 bytes into 16 bytes hexadecimal integers. Kindly help. Here is my code:

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;

}

Upvotes: 0

Views: 394

Answers (2)

alk
alk

Reputation: 70893

A C-"string" of 16 characters length is 16bytes!

To have it converted to a "byte"-array (of 16 entries lenght) you might like to do the following:

#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;
}

Upvotes: 0

moooeeeep
moooeeeep

Reputation: 32502

If you are looking for printing integer numbers in hexadecimal form, this might help:

#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;
}

If all you want is to turn a char array to an array of 1-byte integer numbers, then you are already done. char already is an integral number type. You can use the buffer you already have, or use malloc/memcpy to copy the data to a new one.

You might want to have a look at the explicit width integer types defined in stdint.h, e.g., uint8_t for a one byte unsigned integer.

Upvotes: 1

Related Questions