位序转字符串的一种高效方法

#include <stdio.h>
#include <stdlib.h>
#include <malloc.h>
#include <string.h>
#include <arpa/inet.h>

#define ROW_UNIT    512
#define UNIT_LENGTH 500
/* 其中ROW_UNIT为使用的位长度,是64的整数倍,但乘积大于UIIT_LENGTH
   UNIT_LENGTH为需要转换的位长度。
   UNIT_LENGTH为需要转换的位长度。也可以是64 64 等,
   ROW_UNIT 需要不小于 UNIT_LENGTH
  */
unsigned long long bits_str[256];
static inline int bits_to_str_init(void)
{
        int i, low, high;
        int bit_str[16] = {
                0x00000000, 0x00000001, 0x00000100, 0x00000101,
                0x00010000, 0x00010001, 0x00010100, 0x00010101,
                0x01000000, 0x01000001, 0x01000100, 0x01000101,
                0x01010000, 0x01010001, 0x01010100, 0x01010101,
        };

        memset(bits_str, '0', sizeof(bits_str));
        for(i=0; i<256; ++i) {
                low = i&0x0F;
                high = i&0xF0;
                high >>= 4;
                *(int *)&bits_str[i] += htonl(bit_str[high]);
                *((int *)&bits_str[i] + 1) += htonl(bit_str[low]);
        }
        return 0;
}

static inline int bitstostr(char *str, unsigned char *bits)
{
        int i;
        unsigned long long *pos = (unsigned long long *)str;
        int c = ROW_UNIT>>3;
        for(i=0; i<c; ++i) {
                *pos = bits_str[(int)(*bits)];
                ++pos;
                ++bits;
        }
        str[UNIT_LENGTH] = 0;
        return 0;
}

int main(int argc ,char *argv[])
{
	if(bits_to_str_init() < 0) return -1;
	unsigned char bits[64];
	int i;
	for(i=0; i<64; ++i) {
		bits[i] = i;
	}
	char str[512];
	bitstostr(str, bits);
	for(i=0; i<strlen(str); ++i) {
		printf("%c", str[i]);
		if(((i+1)&0x7) == 0) printf("\n");
	}
	
	return 0;
}

你可能感兴趣的:(c,include)