How do you apply checkksum to a char in c?
A checksum reduces a sequence of bits to a shorter sequence, such that a change to the larger sequence results in a random change to the shorter checksum.
A char is already quite small. To produce a checksum you will need a bitfield. Actually, you will need two, since one bitfield alone will be padded at least to a full byte.
struct twochars_checksum {
unsigned sum_a : CHAR_BIT / 2;
unsigned sum_b : CHAR_BIT / 2;
};
void sum_char( char c, struct twochars_checksum *dest, int which ) {
int sum;
sum = c ^ c >> CHAR_BIT / 2; // suboptimal, but passable
if ( which == 0 ) {
dest->sum_a = sum;
} else {
dest->sum_b = sum;
}
}
Suggest to follow similar approach to transfer a byte of data with checksum.
The algorithm for calculating checksum is quite simple and is as follows.
1.Check if the bit is on then add the corresponding bit value ( ie 2 to the power of bit position ) to the check sum.
2.If the bit is off then detect the sum by 1.
Note : You can use your own checksum algorithm by altering function calculate_checksum().
You can include your own processing logic in set_transfer_data().
#include <stdio.h>
typedef unsigned char uint8_t;
typedef unsigned short uint16_t;
typedef unsigned int uint32_t;
#define NUM_BITS (8)
uint16_t calculate_checksum(const uint8_t data)
{
uint16_t checksum = 0;
uint8_t bit_index = 0;
uint8_t bit_value = 0;
while( bit_index < NUM_BITS )
{
bit_value = 1 << bit_index++;
checksum += ( data & bit_value ) ? bit_value : -1;
}
return ( checksum );
}
uint8_t set_transfer_data( uint32_t *dest_data , const uint8_t src_data , const uint16_t checksum )
{
uint8_t return_value = 0;
*dest_data = checksum << NUM_BITS | src_data ;
return ( return_value );
}
int main()
{
uint8_t return_value = 0;
uint8_t source_data = 0xF3;
uint32_t transfer_data = 0;
uint16_t checksum = 0;
checksum = calculate_checksum( source_data );
printf( "\nChecksum calculated = %x",checksum );
return_value = set_transfer_data( &transfer_data,source_data,checksum );
if( 0 == return_value )
{
printf( "\nChecksum added successfully; transfer_data = %x",
transfer_data );
}
else
{
printf( "\nError adding checksum" );
}
return ( 0 );
}