2013年11月13日 星期三

HEX轉成文字檔

J-Link取得資料,在PC上存成HEX格式。
寫了小程式轉成資料,可以用於Excel上看。

#include <stdio.h>
#include <string.h>
#include <fcntl.h>
#include <windows.h>

#define  SIZE                (0x1000000)
#define  MEM_SIZE            (0x10000)

unsigned char data[SIZE];
unsigned char image[MEM_SIZE];
FILE *src;
FILE *dest;

unsigned char *p_data;
unsigned char *p_src;

unsigned char B2bin(unsigned char *x)
{
    int t;
    int i;
    unsigned short r;

    r = 0;
    for ( i=0; i<2; i++ )
    {
        if ( *x <= '9' )
        {
            t = (*x-'0');
        }
        else
        {
            t = (*x-'A'+0xA);
        }
        r = (r<<4) + t;
        x++;
    }
    return r;
}

unsigned short W2bin(unsigned char *x)
{
    int t;
    int i;
    unsigned int r;

    r = 0;
    for ( i=0; i<4; i++ )
    {
        if ( *x <= '9' )
        {
            t = (*x-'0');
        }
        else
        {
            t = (*x-'A'+0xA);
        }
        r = (r<<4) + t;
        x++;
    }
    return r;
}

void main(void)
{
    int  i,j,n;
    char temp[80];
    int  byte_count;
    unsigned short address;
    int  record_type;
    int  flag;
    unsigned int img_address;
    int  first_address_flag = 0;
    unsigned int first_address;
    unsigned short *w_data;

    p_data     = &image[0];
    src = fopen("memory.hex", "rb");
    fread(data,1,SIZE,src);
    fclose(src);
    p_src = &data[0];
    temp[0] = 0;
    flag = 1;
    while ( flag )
    {
        sscanf(p_src,"%s",temp);
        n = strlen(temp);
        if ( n == 0 )
        {
            break;
        }
//        printf("%s\n",temp);
        if (':' != temp[0]) continue;
        byte_count = B2bin(&temp[1]);
        address    = W2bin(&temp[3]);
        record_type= B2bin(&temp[7]);
        switch ( record_type )
        {
        case 0:  // data record
            if(! first_address_flag )
            {
                first_address = img_address + address;
                first_address_flag = 1;
            }
            for( j=0; j<byte_count; j++ )
            {
                p_data[img_address+address+j-first_address] = B2bin(&temp[9+j*2]);
            }
            break;
        case 1:  // end
            flag = 0;
            break;
        case 4:  // relocate
            img_address = ((W2bin(&temp[9]))<<16);
            break;
        default:
            break;
        }
        // reset var.
        p_src += (n+2);
        temp[0] = 0;
    }
    dest = fopen("audio.csv", "w");
    w_data = (unsigned short *) &image[0];
    for( i=0; i<MEM_SIZE/2; i++)
    {
        if(*w_data == 0 ) break;
        fprintf(dest,"%d\n",*w_data);
        w_data++;
    }
//    fwrite(image, 1, MEM_SIZE, dest);
    fclose(dest);
}

沒有留言:

張貼留言