close

updated 2009/02/14

更新並加入一些功能 V1.2

應該會是相當實用的小工具(最近自己很常用)


 updated 2008/12/06

做一點小改版


 

這陣子剛剛入門BCB,有別於之前都是在寫韌體都是用C語言

這次要用C++寫視窗介面程式

這是我為自己定的一個小功課 -- Ascii 轉16進制 & 16進制轉Ascii

Ascii Converter v1.1.rar 

Ascii Converter v1.2.rar C-マンション

上面是我草寫的小工具,以下參考看看我的寫法吧

高手們還請多指教

◎輸入字元,以16進制字元輸出

void __fastcall TRANSCHAR::BytesToStr(unsigned long len ,char *_from ,char *_dest)
{
 char *p_str;
 unsigned long i;
 int tmp;

    p_str = _from;
    for(i=0 ;i<len ;i++)
    {
        tmp = (*p_str & 0xF0) >> 4;
        *_dest++ = (tmp <= 9) ? tmp+'0':(tmp-10)+'A';
        tmp = *p_str & 0x0F;
        *_dest++ = (tmp <= 9) ? tmp+'0':(tmp-10)+'A';
        *_dest++ = ' ';                           //加入空格區隔
        p_str++;
    }
    *_dest++ = 0; }

_from指向輸入的字元,副程式中將位址給p_str處理,len為輸入的長度,轉換的結果指向_dest,轉換的結果由_dest取得

◎輸入16進制字元,輸出對應的ASCII字元

char __fastcall TRANSCHAR::HexToStr(char *hex_str)
{
 int hex_int;
 char temp[2];
    sscanf(hex_str ,"%X" ,&hex_int);
    sprintf(temp ,"%c" ,hex_int);
    return *temp;
}

將16進制字串丟進去會回傳對應的ASCII,例如: char a[3]="41"; char b=HexToStr(a);

此時b會得到'A'

寫好了這2個基本Function,就可以來完成主程式了

void __fastcall TForm1::Btn_Asc2HexClick(TObject *Sender)
{
 int len;
 char show_box[4096];

    len = Memo1->Text.Length();     //取得輸入長度
    Trans->BytesToStr(len ,Memo1->Text.c_str() ,show_box);  //轉換成ASCII字元
    Memo2->Text = show_box;
    Label1->Caption = IntToStr(len);

}
//---------------------------------------------------------------------------
void __fastcall TForm1::Btn_Hex2AscClick(TObject *Sender)
{
 int i=0;
 char get_hex[4096] ,show_hex[128] ,get_char;
 char *p_memo1 ,*p_str;

    strcpy(get_hex ,Memo1->Text.c_str());
    p_memo1 = get_hex;

            while(1)
            {
             p_str = strchr(p_memo1 ,' ');  //抓取空白字元位址來判斷一個byte的輸入

                if(p_str == NULL)
                {
                    if(*p_memo1 > ' ')
                    {
                    get_char = Trans->HexToStr(p_memo1);
                    show_hex[i++] = get_char;
                    }
                 break;
                }

                if(*p_memo1 > ' ')
                {
                 get_char = Trans->HexToStr(p_memo1);
                 show_hex[i++] = get_char;
                }
             p_memo1 = p_str+1;
            }

    Label1->Caption = IntToStr(i);
    show_hex[i++] = '\0';
    Memo2->Text = show_hex;
}
//---------------------------------------------------------------------------

如此大致大完成了字元互轉的功能,請大家不吝指教,參考參考囉!

 

 

arrow
arrow
    全站熱搜

    orangeprince 發表在 痞客邦 留言(4) 人氣()