Char array into byte array

Hi,

I want to write a " C" code to convert char array into unsigned char array. Actually I want to write a function. How can I do this. I tried with google but it's not work for me. Please help.

Thank you.
A simple C style cast will do the job (in C++ use reinterpret_cast).

Hi,

Thanks for reply. this is my code.

1
2
3
4
5
6
7
8
9

char *str = "1A2B";

unsigned char *newStr;

newStr = ( unsigned char *) str ;

printf("%2x",newStr[0]); // Output is 30


I want to do this.

I have char array. I have to pass it into smart card as a byte array. So I want to convert it into byte array. So how can I do this?

thank you.

Last edited on
Do you want to convert a hex reprezentation of a string to unsigned char* ? I really don't follow you what you really want.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <stdio.h>
#include <stdlib.h>

typedef unsigned char u8;
inline u8 a(char **b) { u8 r; if(**b>071) r= **b-0x37; else r = **b-060; (*b)++; return r; }
void s2u(char *s, u8 *o)
{
   for(;*s;o++) *o = (a(&s) << 4)|a(&s);
}
int main()
{
    char test[] = "4A464946";
    u8* res = (u8*)malloc (128);
    s2u (test, res);
    printf ("%s", res);
    free (res);
}
Hi,

Thanks for the code . But in my case I can't use malloc, new functions. Because This is a POS terminal application. I also have this code but it's not good. Sometimes it works sometimes not.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

int charToByteArray(unsigned int bytearray[],char *hexstring){
    int i;
	
    uint8_t str_len = strlen(hexstring);

	memset(bytearray, 0x00, sizeof(bytearray));

    for (i = 0; i < ((str_len / 2)-1); i++) {
        sscanf(hexstring + 2*i, "%02x", &bytearray[i]);
    }

    return 1;
}


Any ideas?

Thank you.
Hi,

Finally I found a solution. But I don't think it's a good idea. But in this situation it is perfect.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
int convertZeroPadedHexIntoByte(char *dataset,unsigned char *bytearray){
	int i = strlen(dataset),j=0,counter=0;
	char c[2];
	unsigned int bytes[2];

	for(j=0;j<i;j++){
		if(0 == j%2){

			c[0] = dataset[j];
			c[1] = dataset[j+1];

			sscanf(c, "%02x", &bytes[0]);

			bytearray[counter] = bytes[0];

			counter++;
		}
	}

}


Modoran Thank you very very much :)
Last edited on
Topic archived. No new replies allowed.