[C] HexToAscii / hex2ascii / hex2str / hex변환 / hex convert

2020. 9. 10. 15:02🧑🏻‍💻/C & C++

/*******************************************************************************
* Function Name: HexToAscii()
********************************************************************************
* Summary:
* Hexadecimal to ASCII converter
*
* Parameters:
* uint32 value: Hexadecimal value
* uint8 digit: Which nibble to be obtained
*
* Return:
* char: the ASCII equivalent of that nibble
*
* Theory:
* Converts hexadecimal to ASCII
*
*******************************************************************************/
char HexToAscii(uint8 value, uint8 nibble)
{
    if(nibble == 1)
    {
        value = value & 0xf0;
        value = value >> 4;
        
        /*bit-shift the result to the right by four bits (i.e. quickly divides by 16)*/
        if (value >9)
        {
            value = value - 10 + 'A';
        }
        else
        {
            value = value + '0';
        }
    }
    else if (nibble == 0)
    {
        /*means use a bitwise AND to take the bottom four bits from the byte,
        0x0F is 00001111 in binary*/
        value = value & 0x0F;
        if (value >9)
        {
            value = value - 10 + 'A';
        }
        else
        {
            value = value + '0';
        }
    }
    else
    {
        value = ' ';    
    }
    
    return value;
}
​
/*******************************************************************************
* Function Name: HandleUartRxbuffer
********************************************************************************
*
* Summary:
*
* Parameters:
*  None.
*
* Return:
*   None.
*
*******************************************************************************/
void HandleUartRxbuffer(void)
{    
	if(received_character == 1)
	{
		received_character = 0;
		if((read_character != ']'))// && ( read_character != '\n')) 
		{ // Ignore CR and LF		 
			rxBuffer[Uart_Rx2Cnt++] = read_character;
			//printf("%x",read_character);
		}        
//		if(read_character == '\n')
        if(read_character == ']')
		{	
            printf("rxBuffer =  ");
            for(int i = 0; i<Uart_Rx2Cnt ;i++)
            {
                UART_UartPutChar(HexToAscii(rxBuffer[i],1));
                UART_UartPutChar(HexToAscii(rxBuffer[i],0));
                UART_UartPutChar(':');
            }
            printf("length -> %d \r\n",Uart_Rx2Cnt);
            rtCamperReceiverMgr(rxBuffer,Uart_Rx2Cnt);
		}
	}        
}