HEX assignment to C

I created a long byte sequence that looks like this:

0x401DA1815EB560399FE365DA23AAC0757F1D61EC10839D9B5521F..... 

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

Obviously, I get a warning that the hex escape sequence is out of range when I do it here.

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

Format required

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

So I'm wondering if in C there is a way for this job without me adding a hexadecimal escape sequence after each byte (may take some time)

+4
source share
4 answers

I do not think that there is a way to make it literal.

You can parse the string at runtime and save 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 
+7
source

AFAIK, no.

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

+4
source

There is no way to do this in C or C ++. The obvious solution is to write a program to insert the "\ x" sequences at the correct point on the line. This would be a suitable task for a scripting language such as perl, but you can also easily do this in C or C ++.

+2
source

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

If a sequence changes dynamically, you can relatively easily convert it at run time.

 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; } 
+2
source

Source: https://habr.com/ru/post/1299639/


All Articles