固定連結網頁

2017年6月14日 星期三

C語言 字串轉十六進位 (string to hex array)

有時要把使用者輸入的訊息送出,需要先從字串轉換成16進制的數值。
記錄一下 string to hex array by ANSI C:

#include <stdio.h> 
#include <stdlib.h>
#include <string.h>

#define u16 unsigned short
#define u32 unsigned int

#define BYTE_SWAP_16(x) \
     (u16) ( ((((u16)(x)) & 0x00ff) << 8 ) | \
             ((((u16)(x)) & 0xff00) >> 8 ) \
          )

#define BYTE_SWAP_24(x) \
     (u32) (\
     (( ((u32)(x)) & 0x00ff0000 ) >> 16 ) | \
     (( ((u32)(x)) & 0x0000ff00 ) >> 0 ) | \
     (( ((u32)(x)) & 0x000000ff ) << 16) \
    )
#define BYTE_SWAP_32(x) \
     (u32) (\
     (( ((u32)(x)) & 0xff000000 ) >> 24) | \
     (( ((u32)(x)) & 0x00ff0000 ) >> 8 ) | \
     (( ((u32)(x)) & 0x0000ff00 ) << 8 ) | \
     (( ((u32)(x)) & 0x000000ff ) << 24) \
    )

    
int StrHex(char* str, unsigned char *HexData, unsigned int endian_swap_enable){
    //char str[] ="a,b,c,d*e"; 
    const char * split = " "; 
    char * p;
    unsigned int Hex,len;
    int HexData_len =0;
    int i;
    printf("%s \r\n",str);
    p = strtok (str,split); 
    while(p) { 
        //printf ("%s\n",p); 
        Hex = strtol(p, NULL, 16);
        //printf("%x\n", Hex);
        len = (strlen(p)+1)>>1;len = (strlen(p)+1)/2;
        //------------------------
        // swap
        if(endian_swap_enable){
            //------------
            if(len <= 1) ;
            else if(len == 2) Hex = BYTE_SWAP_16(Hex);
            else if(len == 3) Hex = BYTE_SWAP_24(Hex);
            else if(len == 4) Hex = BYTE_SWAP_32(Hex);
        }
        //------------------------
        if(len > 4){
            printf("Error!");
            return -1;
        }
        memcpy(&HexData[HexData_len], &Hex, len);
        HexData_len += len;
        
        p = strtok(NULL,split); 
    }
        
    for(i=0;i<HexData_len;i++){
        printf("%02x ", (unsigned char) HexData[i]);
    }
    return HexData_len;
}

int main()
{
    char buf[1024];
    char str[] = "00 12 123 1234 12345 123456 1234567 12345678";
    //char str[] = "00 1234567890";
    StrHex(str, (unsigned char*)buf, 1);
    return 0;
}


log:

00 12 123 1234 12345 123456 1234567 12345678
00 12 01 23 12 34 01 23 45 12 34 56 01 23 45 67 12 34 56 78
Process returned 0 (0x0)   execution time : 0.031 s
Press any key to continue.

沒有留言:

張貼留言

手機選擇帳號後,按下發布 要再點選一次發布哦