user00011
user00011

Reputation: 123

c++ data structure to hold 128 bits of data

I need a data structure to hold some 120 bits of data.

I have bit manipulations like type var = 0X01000000000000000000000000000000) >> 120

What is the best data structure to hold such a lengthy data?

Upvotes: 1

Views: 544

Answers (4)

P.W
P.W

Reputation: 26800

You can use a std::bitset. It has operators operator<<, operator>> defined for it.

A minimal example:

#include <iostream>
#include <bitset>

int main()
{
    std::bitset<120> b("01000000000000000000000000000000");
    std::cout << "initial value: " << b << '\n';

    b >>= 12;

    std::cout << "final value: "  << b << '\n';        
}

You can see the demo here.

Upvotes: 3

Lanting
Lanting

Reputation: 3068

Unless you specify what exactly you'd like to to with those bits, std::bitset is probably your best bet.

Additionally, gcc and clang support unsigned __int128 on some targets. Though, this is non-standard.

Upvotes: 5

rg_software
rg_software

Reputation: 126

Any reason to avoid std::bitset?

#include <bitset>
...
std::bitset<128> bs;
bs[0] = 1; bs[127] = 1;
std::cout << bs.to_string() << std::endl;
// prints 128 digits with ones on both ends

Upvotes: 0

R Sahu
R Sahu

Reputation: 206627

What is the best data structure to hold such a lengthy data?

Option 1:

struct MyType { uint8_t data[16]; };

Option 2:

struct MyType { uint16_t data[8]; };

Option 3:

struct MyType { uint32_t data[4]; };

Option 4:

struct MyType { uint64_t data[2]; };

Option 5:

struct MyType { std::bitset<128> data; };

It's hard telling which one will best serve you needs without knowing more about them.

Upvotes: 1

Related Questions