tool.h 工具函数的声明

#ifndef __TOOL_H
#define __TOOL_H

#include <stdint.h>
#include <sys/time.h>
#include <string.h>

extern void createData(char * data, uint16_t length);
extern void genRandomString(char *data, int length);
extern float mydifftime(struct timeval *start);
extern uint16_t my_chksum(uint16_t *data, int len);

#endif

tool.c 工具函数的实现

#include <stdio.h>
#include <stdlib.h>
#include <tool.h>
// 生成数据
void createData(char * data, uint16_t length){
    if(length < 1){
        return;
    }
    if(length < 16) {
        genRandomString(data, length);
    } else {
        struct timeval t;
        gettimeofday(&t, NULL);
        memcpy(data,(char *)&t, 16);
        data = data + 16;
        genRandomString(data, (int)(length-16));
    }
}

// 生成随机数
void genRandomString(char *data, int length){
    int flag, i;
    for (i = 0; i < length; i++)
    {
        flag = rand() % 3;
        switch (flag)
        {
            case 0:
                *data = 'A' + rand() % 26;
                break;
            case 1:
                *data = 'a' + rand() % 26;
                break;
            case 2:
                *data = '0' + rand() % 10;
                break;
            default:
                *data = 'x';
                break;
        }
        data++;
    }
}

// 计算时间差
double mydifftime(struct timeval *start) {
    struct timeval endtime;
    gettimeofday(&endtime,0);
    if ((endtime.tv_usec -= start->tv_usec) < 0) {
        endtime.tv_sec --;
        endtime.tv_usec += 1000000;
    }
    endtime.tv_sec -= start->tv_sec;
    return endtime.tv_sec * 1000.0 + endtime.tv_usec / 1000.0;
}

// chksum
uint16_t my_chksum(uint16_t *data, int len) {
    int result = 0;
    while(len > 1){
        result += *data;
        data++;
        len -= 2;
    }
    if ( len ){
        result += *((uint8_t *)data);
    }
    while(result >> 16) result = (result&0xffff) + (result>>16);
    return ~result;
}
文档更新时间: 2021-02-03 15:11   作者:周国强