a bit map in c++ - will unsigned int do the job?
-
12-11-2019 - |
문제
I'm afraid to admit, I haven't used C++ for a while now but i'm afraid I have to now, and I'm a bit rusty.
I need to have a bitmap, and I do care about performance, my bitmap size will be no longer then 25 bits.
I was thinking about using unsigned int, but I am afraid I do not remember how it is implemented in c/c++
Is unsigned int implemented as a regular binary number?
I am also open to any other suggestions for a bitmap.
thanks in advance for the help!
해결책
Use an std::bitset<25>
from the header <bitset>
. bitset
can be indexed with []
and is a template, so it likely expands to just an unsigned int
(or equivalent) with all operations inlined.
다른 팁
Have you considered std::bitset from <bitset>
header file?
Example:
#include <iostream>
#include <bitset>
int main() {
std::bitset<25> bits(146);
std::cout << bits << std::endl;
//using operator[] to access individual bit manually!
for(size_t i = 0 ; i < bits.size() ; ++i)
std::cout << bits[i] << " ";
return 0;
}
Output:
0000000000000000010010010
0 1 0 0 1 0 0 1 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
Note: bits[0]
is the least significant bit, while bits[bits.size()-1]
is the most significant bit!
Online demo : http://ideone.com/3sSF0
consider a bitset instead.
You should be able to use an integer type for a bit map, assuming it has enough bits for you.
However, there is a <bitset>
in the standard library.