I am trying to convert a string of length 128bytes to a byte array. For eg: if my string is "76ab345fd77......" so on. I want to convert it to a byte array , so it should look something like {76 ab 34 45 ....} and so on upto 64 bytes. I have written the following code but the byte array always shows value as 1 instead of 76 ab .... Any suggestions as to what I am doing wrong here or if there is a better way to achieve this:
char* newSign; // It contains "76ab345fd77...."
int len = strlen(newSign); //len is 128
int num = len/2;
PBYTE bSign;
//Allocate the signature buffer
bSign = (PBYTE)HeapAlloc (GetProcessHeap (), 0, num);
if(NULL == bSign)
{
wprintf(L"**** memory allocation failed\n");
return;
}
int i,n;
for(i=0,n=0; n<num ;i=i+2,n++)
{
bSign[n]=((newSign[i]<<4)||(newSign[i+1]));
printf("newsign[%d] is %c and newsign[%d] is %c\n",i,newSign[i],i+1,newSign[i+1]);
printf("bsign[%d] is %x\n",n,bSign[n]);
//sprintf(bSign,"%02x",()newSign[i]);
}
Thanks a lot for all the replies. The following code worked for me:
BYTE ascii_to_num(char c)
{
if ('0' <= c && c <= '9')
return c - '0';
if ('a' <= c && c <= 'f')
return c -('a'-('0'+10));
}
for(i=0,n=0; n<num ;i=i+2,n++)
{
BYTE a = (ascii_to_num(newSign[i])) & 0x0F;
BYTE b = ascii_to_num(newSign[i+1]) & 0x0F;
bSign[n] = (a<<4) | (b);
printf("bsign[%d] is %x\n",n,bSign[n]);
}
newSign[i]<<4||newSign[i+1]- you forgot to convert from an ASCII character code to a numeric value... you will need to use something likeint ascii_to_num(char c) { if ('0' <= c && c <= '9') return c - '0'; if ('a' <= c && c <= 'f') return c - 'f'; throw std::runtime_error("invalid hex digit"); }thenascii_to_num(newSign[i]<<4) | ascii_to_num(newSign[i+1])(note single|for bitwise-OR).atoionly converts decimal numbers, and evenstrtol- which can convert hex numbers - has no support for converting exactly 2 digits at a time (you could write aNUL\0terminator into the string temporarily then use it then restore the previous character, but it's more trouble than it's worth IMHO).for (...) { std::stringstream ss; ss << newSign[i] << newSign[i + 1]; char c; if (!(ss >> std::hex >> bSign[n]) || (ss >> c)) throw std::runtime_error("bad hex value"); }