对于一些标准的数据类型,例如unsigned int, unsigned short, unsigned long 等,我们可以将其重命名成为简易拼写的字母,这样在使用的时候,既减少了拼写,又显得清楚明了,下面是我常用的头文件的定义:
my_basetype.h
#ifndef _BASETYPE_H_
#define _BASETYPE_H_
/*****************************C99 /usr/include/stdint.h*****************************/
#ifndef __int8_t_defined
# define __int8_t_defined
typedef signed char int8_t;
typedef short int int16_t;
typedef int int32_t;
# if __WORDSIZE == 64
typedef long int int64_t;
# else
__extension__
typedef long long int int64_t;
# endif
#endif
typedef unsigned char uint8_t;
typedef unsigned short int uint16_t;
#ifndef __uint32_t_defined
typedef unsigned int uint32_t;
# define __uint32_t_defined
#endif
#if __WORDSIZE == 64
typedef unsigned long int uint64_t;
#else
__extension__
typedef unsigned long long int uint64_t;
#endif
/************************************************************************************/
#ifndef USHORT
#define USHORT unsigned short
#endif
#ifndef UINT
#define UINT unsigned int
#endif
#ifndef ULONG
#define ULONG unsigned long
#endif
#ifndef UCHAR
#define UCHAR unsigned char
#endif
#ifndef VOID
#define VOID void
#endif
#ifndef SHORT
#define SHORT short
#endif
#ifndef INT
#define INT int
#endif
#ifndef LONG
#define LONG long
#endif
#ifndef CHAR
#define CHAR char
#endif
#ifndef BOOL
#define BOOL bool
#endif
#ifndef SUCCESS
#define SUCCESS 0
#endif
#ifndef ERROR
#define ERROR 1
#endif
#ifndef UINT64
#define UINT64 uint64_t
#endif
#define IN
#define OUT
#define INOUT
#ifndef BIT_TEST
#define BIT_TEST(a, b) ( 0 != ((a) & (b)))
#endif
#ifndef BIT_SET
#define BIT_SET(a, b) ((a) |= (b))
#endif
#ifndef BIT_RESET
#define BIT_RESET(a, b) ((a) &= ~(b))
#endif
#ifndef BIT_MATCH
#define BIT_MATCH(a,b) (( (a) & (b) ) == (b))
#endif
#ifndef BIT_COMPARE
#define BIT_COMPARE(a,b,c) (( (a) & (b) ) == (c))
#endif
#endif // end of _BASETYPE_H_
测试文件main_test.c,这里将两个unsigned int 数据保存在一个 64位长整型内,然后再分别获取出来。SET与GET分别对应宏定义。
#include <stdio.h>
#include <string.h>
#include "my_basetype.h"
#define GET_UINT_RIGHT_MOVE_32(a) (UINT)(a >> 32)
#define GET_UINT_CUT(a) (UINT)(a)
#define SET_UINT_LEFT_MOVE_32(a, b) \
{\
a = (UINT64)(((UINT64)b << 32));\
}
#define SET_UINT_CUT(a, b) \
{\
a |= (UINT64)b;\
}
int main(void)
{
UINT a = 1;
UINT b = 3;
UINT64 c = 0;
c = (UINT64)(((UINT64)a << 32)|(UINT64)b);
//SET_UINT_LEFT_MOVE_32(c, a);
//SET_UINT_CUT(c, b);
printf("a= %#x, b = %#x, c = %#lx\n", a, b, c);
printf("reback numbers\n");
a = GET_UINT_RIGHT_MOVE_32(c);
b = GET_UINT_CUT(c);
printf("a= %#x, b = %#x, c = %#lx\n", a, b, c);
return 0;
}
测试结果:
li@li:~/C$ gcc *.c
li@li:~/C$ ./a.out
a= 0x1, b = 0x3, c = 0x100000003
reback numbers
a= 0x1, b = 0x3, c = 0x100000003