在做数据压缩的时候, 需要找到最小存储单元, 在网上看了,没找到合适的,这里把我想到的一种方式供大家参考。
#include <cstdio>
#include <iostream>
using namespace std;
char bin_left_one(u_int64_t num){
char pos = 0;
u_int64_t t = num;
for(int i = 5; i >= 0; i--){
if(num >> (1<<i)) {pos += (1<<i);num >>= (1<<i);}
}
return pos+1;
}
int main(){
for(int i = 0; i < 64; i++){
char pos = bin_left_one(1LLU<<i);
cout << "["<< hex << (1LLU<<i) << "] pos: " << dec << (int)(pos) << endl;
}
return 0;
}
输出样式:
[1] pos: 1
[2] pos: 2
[4] pos: 3
[8] pos: 4
[10] pos: 5
[20] pos: 6
[40] pos: 7
[80] pos: 8
[100] pos: 9
[200] pos: 10
[400] pos: 11
[800] pos: 12
... ...
比如我要做数据压缩时的样例:
#include <cstdio>
#include <iostream>
#include <math.h>
using namespace std;
char bin_left_one(u_int64_t num){
char pos = 0;
u_int64_t t = num;
for(int i = 5; i >= 0; i--){
if(num >> (1<<i)) {pos += (1<<i);num >>= (1<<i);}
}
return pos+1;
}
int main(){
size_t a = 0x102030;
char pos = bin_left_one(a);
printf("数据本身: %#lx\n", a);
printf("内存数据: ");
for(int i = 0; i < sizeof(a); i++){
printf("%02x ", ((char*)&a)[i]);
}
printf("\n");
printf("压缩数据: ");
for(int i = ceil(pos/8.0)-1; i >= 0 ; i--){
printf("%02x ", ((char*)&a)[i]);
}
printf("\n");
return 0;
}
打印效果:
数据本身: 0x102030
内存数据: 30 20 10 00 00 00 00 00
压缩数据: 10 20 30