티스토리 뷰

일하면서

[short code] BCD encoding

신랑각시 2017. 12. 5. 21:23

안녕하세요.

신랑각시의 신랑 입니다.


일하면서, 이진 값 배열 (binary stream) 을 printable string 으로 변환해야 할 일이 생겼습니다.


이런 경우에는 BCD 을 하여, 값을 변환하여 처리하곤 합니다.


예를 들면,


 0x93, 0x17, 0x52, 0xF4 


라는 이진 배열 ( 4 byte ) 이 있을 때, 이 값을 printable string 으로 변환하기 위하여 BCD encoding 을 하면,


 0x39, 0x33, 0x31, 0x37, 0x35, 0x32, 0x46, 0x34  


로 변환됩니다. 각각의 값은 ascii 표를 통하여 보면, 931752F4 로 print 됩니다.


4 bit 값 ( max 0xF ) 을 8 bit 로 표현하다 보니까, 길이가 2배로 늘어납니다.


그럼 C++ 코드 입니다.


BCD encoding


const char * BCD2STR(char * _dest, char * _src, int _len)
{
    static const char * out = "0123456789ABCDEF";

    for(int pos = 0; pos < _len; pos++)
    {
        *_dest++ = out[(_src[pos] >> 4) & 0x0f];
        *_dest++ = out[_src[pos] & 0x0f];
    }

    *_dest = '\0';
    return _dest - (_len * 2);
}


BCD decoding


const unsigned char * STR2BCD(unsigned char * _dest, char * _src, int _len)
{
    char h, l;

    for(int pos=0; pos < _len; pos++)
    {
        h = _src[pos*2];
        l = _src[pos*2+1];

        h = ( (h & 0xf0) == 0x30 )?(h & 0x0f):(9 + (h & 0x0f));
        l = ( (l & 0xf0) == 0x30 )?(l & 0x0f):(9 + (l & 0x0f));

        *_dest++ = (unsigned char)(((h & 0x0f) << 4) | l);
    }

    return (_dest - (_len/2));
}


댓글