tags:

views:

191

answers:

4

Hi,

I have generated a long sequence of bytes which looks as follows:

0x401DA1815EB560399FE365DA23AAC0757F1D61EC10839D9B5521F.....

Now, I would like to assign it to a static unsigned char x[].

Obviously, I get the warning that hex escape sequence out of range when I do this here

static unsigned char x[] = "\x401DA1815EB56039.....";

The format it needs is

static unsigned char x[] = "\x40\x1D\xA1\x81\x5E\xB5\x60\x39.....";

So I am wondering if in C there is a way for this assignment without me adding the hex escape sequence after each byte (could take quite a while)

+2  A: 

No there is no way to do that in C or C++. The obvious solution is to write a program to insert the '\x' sequences at the correct point in the string. This would be a suitable task for a scripting language like perl, but you can also easily do it in C or C++.

anon
+7  A: 

I don't think there's a way to make a literal out of it.

You can parse the string at runtime and store it in another array.

You can use sed or something to rewrite the sequence:

echo 401DA1815EB560399FE365DA23AAC0757F1D61EC10839D9B5521F | sed -e 's/../\\x&/g'
\x40\x1D\xA1\x81\x5E\xB5\x60\x39\x9F\xE3\x65\xDA\x23\xAA\xC0\x75\x7F\x1D\x61\xEC\x10\x83\x9D\x9B\x55\x21F
strager
+4  A: 

AFAIK, No.

But you can use the regex s/(..)/\\x$1/g to convert your sequence to the last format.

KennyTM
Best way, use a regex app and then cut and paste the result into your code
Patrick
+2  A: 

If the sequence is fixed, I suggest following the regexp-in-editor suggestion.

If the sequence changes dynamically, you can relatively easily convert it on runtime.

char in[]="0x401DA1815EB560399FE365DA23AAC0757F1D61EC10839D9B5521F..."; //or whatever, loaded from a file or such.

char out[MAX_LEN]; //or malloc() as l/2 or whatever...

int l = strlen(in);
for(int i=2;i<l;i+=2)
{
    out[i/2-1]=16*AsciiAsHex(in[i])+AsciiAsHex(in[i]+1);
}
out[i/2-1]='\0';
...

int AsciiAsHex(char in)
{
   if(in>='0' && in<='9') return in-'0';
   if(in>='A' && in<='F') return in+10-'A';
   if(in>='a' && in<='f') return in+10-'a';
   return 0;
}
SF.