简体   繁体   中英

How to convert a string into a byte array in C++

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]);
        }

The code:

bSign[n]=((newSign[i]<<4)||(newSign[i+1]));

Will not convert hex characters into a byte. Note also you want the bitwise or | instead of a logical or ||. For the decimal digits It's more like

bSign[n]=(((newSign[i]-'0')<<4)|((newSign[i+1]-'0'));

but you also need to take care of the af values. For that you'll want to write a function to turn a hex character into a value

eg.

int hexToVal(char c)
{
    c = (c | 0x20) - '0';
    if (c<0) error;
    if (c>9) {
        c -= ('a'-('0'+10));
        if (c<10 || c>15) error;
    } 
    return c;
}


   bSign[n]=((hexToVal(newSign[i])<<4)|hexToVal(newSign[i+1]));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM