Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How is an hex string assigned to a char array 1

Status
Not open for further replies.

jbmjlm10

Programmer
Jun 16, 2004
11
US
I know how to assign a character string to an array -- one way would be like this:
char_str[] = "whatever string you want to assign";
But how does one assign a hex string? I tried this but it did not work:
char_str[] = 0x"003A00BE00C300C700C9";
Strangely enough, I do need those x'00' bytes within the array, even though in a C string x'00' indicates end of string. There's got to be a way to tell the compiler that those characters within the quotes are hexadecimal values. Come to think of it, that may not be possible (because of the null x'00') even if I knew how to tell the compiler that the string is hexadecimal. I may need to use a pointer and use memcpy to move the hex string into whatever pointer is point to. But there I would have the same problem: how do I indicate to memcpy that "003A00BE00C300C700C9" is hexadecimal? Thank you for your help.
 
You're right that you can't use string functions on such a string, but C has no problem initialising an array of chars filled with nuls.

Code:
#include <stdio.h>
#include <string.h>
int main(void)
{
    char str1[] = "\x00\x3A\x00\xBE\x00\xC3\x00\xC7\x00\xC9";  // C adds a trailing \0 for you
    char str2[10] = "\x00\x3A\x00\xBE\x00\xC3\x00\xC7\x00\xC9";// no extra \0 here
    printf( "%u %u %u\n", sizeof(str1), sizeof(str2), strlen(str1) );
    return 0;
}

You can then do
memcpy( ptr, str, 10 );

--
 
Salem, thank you very much for your reply and for the c code you provided. It was exactly the answer I was looking for -- and more!!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top