我必须创建一个数据结构来存储1万亿用户的生日。如何做到这一点?
如果我使用struct数据类型,那么它将需要6个字节。
struct{
int day,month,year;
}那么6*1万亿=6万亿字节?
那么有没有什么优化的方法或者其他的方法呢?
发布于 2015-05-24 13:48:08
假设天为5位,月为4位,年为12位,则每个用户需要21位。填充到8位的倍数时,每个条目有24位=3字节。
这意味着,您需要大约3TB来存储所有数据(如果我没有计算错误的话)。
发布于 2015-05-24 14:13:08
基于Hannu的回答:(5比特表示日,4比特表示月份,7比特表示年份)
const unsigned long int n = 1e2;
// store (n * 2 bytes)
unsigned short birthdays[n];
static_assert( sizeof(short) == 2, "failure." );
// user input
int day = 31; // requirement: 5 bits
int month = 12; // requirement: 4 bits
int year = 127; // requirement: 7 bits. actual year = 1940(starting year) + 127 = 2067 (max year)
// store
// birthdays[0] = day + month * 32 + year * 512;
birthdays[0] = day + (month << 5) + (year << 9);
// how it looks
std::bitset<16> binary(birthdays[0]);
cout << "raw record: " << birthdays[0] << " (binary view = " << binary << ")" << endl;
// retrieve
day = (unsigned short)(birthdays[0] << 11) >> 11;
month = (unsigned short)(birthdays[0] << 7) >> 12;
year = (birthdays[0] >> 9) + 1940;
cout << "day = " << day << endl;
cout << "month = " << month << endl;
cout << "year = " << year << endl;DEMO
https://stackoverflow.com/questions/30420433
复制相似问题