简体   繁体   English

将c中的校验和应用于char

[英]apply checksum in c to a char

您如何将Checkksum应用于c中的char?

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. 1.检查该位是否开启,然后将相应的位值(即位位置的幂2)加到校验和。

2.If the bit is off then detect the sum by 1. 2.如果该位为off,则用1来检测和。

Note : You can use your own checksum algorithm by altering function calculate_checksum(). 注意:您可以通过更改函数calculate_checksum()使用自己的校验和算法。
You can include your own processing logic in set_transfer_data(). 您可以在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 );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM