술텀뱅이 블로그

binary to hex C 언어 본문

Language/C

binary to hex C 언어

우럭망둥이 2015. 10. 2. 09:40

업그레이드 할일이 생겼다. 그런데 우리는 업그레이드 기능이 기본적으로 없다.


강제로 해야하는데 어떻게 할까


Manager DB의 내용을 각 Agent로 내리는 구조이니 요걸 활용해보자


DB에 binary 를 저장해서 내릴려고 했으나 문제가 있었다.


그래서 DB 에 binary의 Hexa 값을 저장한다.


hexa를 내려받은 Agent는 hexa를 binary 화 한다.


요기서 좀 애좀 먹었다.


아래는 binary를 hexa 화 하는 코드


#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

int main(int argc, char* argv[])
{
    int readfile, writefile;
    unsigned char readbuf;
    unsigned char writebuf[2];
    ssize_t readb;
    int i=0;

    if(argc != 2){
        printf("Usage : %s <filename> \n", argv[0]);
        return -1;
    }

    readfile= open(argv[1], O_RDONLY);
    if(readfile == -1){
        printf("read file open error\n");
        return -1;
    }
    writefile= open("./output.txt", O_WRONLY|O_TRUNC|O_CREAT);
    if(writefile == -1){
        perror("error : ");
        printf("write file open error\n");
        return -1;
    }
    while((readb = read(readfile, &readbuf, 1)) > 0){
        if( i!=0 &&  (i%50) == 0){
            write(writefile, "\n", 1);
        }

        // 1byte 씩 읽어서 2byte의 hexa 값으로 저장한다.

        sprintf(writebuf, "%02X", readbuf);
        write(writefile, writebuf, 2);
        i++;
    }

    close(readfile);
    close(writefile);
    return 0;
}

요 코드는 1byte를 읽어서 2byte의 hexa로 변환한다. 왜냐

1byte는 hexa 값 2개로 표현되는데 내가 사용할 hexa는 character 이니까 1byte가 char 두개로 표현된다

따라서 binary 를 hexa로 변환하면 용량이 두배가 된다.

참고로 위의 소스는 100byte 마다 개행문자를 넣는다.

요것 때문에 hexa를 binary로 변환 시 fgets를 썼다.


다음은 hexa를 binary로 변환한다. 여기서 애좀 먹었다.


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

int main(int argc, char* argv[])
{
    FILE* readfd;

    char buf[101];
    unsigned char val;
    char* pos;
    int i, writefd;
    unsigned int j;
    ssize_t slength;

    if(argc != 2){
        printf("Usage : %s <filename> \n", argv[0]);
        return -1;
    }
    readfd= fopen(argv[1], "rb");
    if (readfd == NULL){
        printf("read file error\n");
        return -1;
    }

    writefd= open("decode.txt", O_WRONLY | O_TRUNC | O_CREAT);
    if (writefd == -1){
        printf("writefile error\n");
        return -1;
    }


    // 위의 코드에서 hexa를 100byte 마다 개행을 했으므로 fgets로 쓴다.
    while(fgets(buf, 101, readfd) != NULL){
        pos = buf;       
        slength = strlen(buf);
        for(i=0 ; i<slength/2 ; i++){

            // sscanf 로 2byte의 char를 hexa 값으로 int에 저장한다.
            sscanf(pos, "%02x",&j);

            // 캐스팅
            val = (char)j;

            //읽은 캐스팅 문자를 1바이트 쓴다.
            write(writefd, &val, 1);
            pos = pos+2;
        }

    }


    fclose(readfd);
    close(writefd);

    return 0;
}


Comments