shaiko
Advanced Member level 5
- Joined
- Aug 20, 2011
- Messages
- 2,644
- Helped
- 303
- Reputation
- 608
- Reaction score
- 297
- Trophy points
- 1,363
- Activity points
- 18,302
Hello,
I'm comparing 2 methods for concatenating received UART bytes into 32 bit words.
Method #0 uses unions:
Method #1 - uses shifting:
Although both of the above work - I'd like to know which one do you find better to use and why?
If you'd do it in a different way - please write an example.
I'm comparing 2 methods for concatenating received UART bytes into 32 bit words.
Method #0 uses unions:
Code:
union word_from_bytes
{
uint8_t array_bytes [4] ;
uint32_t concatenated_array_bytes ;
} ;
union word_from_bytes some_union ;
int8_t read_and_concatenate ( bool data_ready , int8_t index , union word_from_bytes * some_union )
{
if ( UARTCharsAvail ( UART0_BASE ) )
{
some_union -> array_bytes [ index ] = UARTCharGet ( UART0_BASE ) ;
if ( index == 3 )
{
index = 0 ;
}
else
{
index ++ ;
}
}
return index ;
}
int main(void)
{
uint8_t current_uart_byte = 0 ;
bool flag = 0 ;
while ( 1 )
{
if ( index == 3 )
{
index = 0 ;
}
else
{
index ++ ;
}
current_uart_byte = read_and_concatenate ( UARTCharsAvail ( UART0_BASE ) , current_uart_byte , & some_union ) ;
if ( some_union.concatenated_array_bytes == 0x20202020 ) // Equivalent to pressing 4 times on the Space button of the keyboard
{
flag = 1 ;
}
}
}
Method #1 - uses shifting:
Code:
void byte_shift ( char direction , uint8_t locations , uint32_t * data )
{
if ( direction == 'r' )
{
* data = ( ( * data ) >> 8 * locations ) ;
}
else if ( direction == 'l' )
{
* data = ( ( * data ) << 8 * locations ) ;
}
}
uint8_t read_and_concatenate ( bool data_ready , uint8_t index , uint32_t * data )
{
uint32_t x = 0 ;
if ( UARTCharsAvail ( UART0_BASE ) )
{
x = ( uint32_t ) UARTCharGet ( UART0_BASE ) ;
* data = ( ( * data ) << 8 ) | x ;
if ( index == 3 )
{
index = 0 ;
}
else
{
index ++ ;
}
}
return index ;
}
int main(void)
{
uint8_t current_uart_byte = 0 ;
bool flag = 0 ;
uint8_t index = 0 ;
uint32_t full_word = 0 ;
while ( 1 )
{
//void byte_shift ( char direction , uint32_t * data )
byte_shift ( 'r' , 1 , & y ) ;
current_uart_byte = read_and_concatenate ( UARTCharsAvail ( UART0_BASE ) , current_uart_byte , & full_word ) ;
if ( full_word == 0x20202020 ) // Equivalent to pressing 4 times on the Space button of the keyboard
{
flag = 1 ;
}
}
}
Although both of the above work - I'd like to know which one do you find better to use and why?
If you'd do it in a different way - please write an example.