// Hex or Decimal을
//ASCII로 변환하는 루틴
// Ex) 숫자 3은 ASCII Code가 0x32임
void NumToASCII( unsigned char value )
{
unsigned char buff;
buff = value & 0x0F;
if( buff < 0xA )
ASCII[1] = buff + 0x30; // if value<10
else
ASCII[1] = buff + 0x37; // if value>10
buff = value & 0xF0;
buff >>= 4;
if( buff < 0xA )
ASCII[0] = buff + 0x30; // if value<10
else
ASCII[0] = buff + 0x37; // if value>10
}
// ex2
char tmp[2] = "";
sprintf(tmp, "%02X", 0xF);
printf("%c%c\n", tmp[0], tmp[1]);
//ex3
unsigned char c = 0x1A;
char first = (0xf0 & c) >> 4;
char second = (0x0f & c);
결과는 다 같고..
두번째 예제정도면 충분할듯;
// Char, Hex간 변환
void Char2Hex(unsigned char ch, char* szHex)
{
static unsigned char saucHex[] = "0123456789ABCDEF";
szHex[0] = saucHex[ch >> 4];
szHex[1] = saucHex[ch&0xF];
szHex[2] = 0;
}
//Function to convert a Hex string of length 2 to an unsigned char
bool Hex2Char(char const* szHex, unsigned char& rch)
{
if(*szHex >= '0' && *szHex <= '9')
rch = *szHex - '0';
else if(*szHex >= 'A' && *szHex <= 'F')
rch = *szHex - 55; //-'A' + 10
else
//Is not really a Hex string
return false;
szHex++;
if(*szHex >= '0' && *szHex <= '9')
(rch <<= 4) += *szHex - '0';
else if(*szHex >= 'A' && *szHex <= 'F')
(rch <<= 4) += *szHex - 55; //-'A' + 10;
else
//Is not really a Hex string
return false;
return true;
}
//Function to convert binary string to hex string
void Binary2Hex(unsigned char const* pucBinStr, int iBinSize, char* pszHexStr)
{
int i;
char szHex[3];
unsigned char const* pucBinStr1 = pucBinStr;
*pszHexStr = 0;
for(i=0; i<iBinSize; i++,pucBinStr1++)
{
Char2Hex(*pucBinStr1, szHex);
strcat(pszHexStr, szHex);
}
}
//Function to convert hex string to binary string
bool Hex2Binary(char const* pszHexStr, unsigned char* pucBinStr, int iBinSize)
{
int i;
unsigned char ch;
for(i=0; i<iBinSize; i++,pszHexStr+=2,pucBinStr++)
{
if(false == Hex2Char(pszHexStr, ch))
return false;
*pucBinStr = ch;
}
return true;
}
출처 : http://enlog.tistory.com/entry/char-hex%EA%B0%84-%EB%B3%80%ED%99%98
'AVR(AT90CAN128)공부' 카테고리의 다른 글
OBD 관련 프로그래밍 정보 (2) | 2010.10.21 |
---|---|
간단한 진수 변환기 (0) | 2010.10.21 |
차량용 B-CAN(Low-speed CAN(ISO11898-3)) 에 대한 정보 (3) | 2010.10.21 |
AT90CAN128 AVR 을 이용한 크루즈 동작 표시기 (5) | 2010.10.21 |
CAN 수신(RX) 에서의 삽질 (0) | 2010.10.20 |