# include <iostream>
# include <vector>
# include <stdio.h>
# include <stdint.h> class Bitmap
{
private : std:: vector< uint8_t > data; uint32_t size; public : Bitmap ( uint32_t size) : size ( size) { uint32_t byteSize = ( size + 7 ) / 8 ; data. resize ( byteSize, 0 ) ; } int setBit ( uint32_t pos, bool value) { if ( pos < 0 || pos >= size) { std:: cerr << "Invalid bit position: " << pos << std:: endl; return - 1 ; } int bytePos = pos / 8 ; int bitPos = pos % 8 ; if ( value) { data[ bytePos] |= ( 1 << bitPos) ; } else { data[ bytePos] &= ~ ( 1 << bitPos) ; } return 0 ; } bool getBit ( uint32_t pos) const { if ( pos < 0 || pos >= size) { std:: cerr << "Invalid bit position: " << pos << std:: endl; return 0 ; } int bytePos = pos / 8 ; int bitPos = pos % 8 ; return ( data[ bytePos] & ( 1 << bitPos) ) != 0 ; } void printBitmap ( void ) { printf ( "Bitmap :\n" ) ; for ( int i = 0 ; i < size; i++ ) { printf ( " %.2d:%d |" , i, getBit ( i) ) ; if ( ( 0 == ( ( i + 1 ) % 8 ) ) && ( 0 != i) ) { printf ( "\n" ) ; } } printf ( "\n" ) ; } int readData ( uint32_t startByte, uint8_t * data, uint32_t dataSize) const { uint32_t bitmapByteSize = ( size + 7 ) / 8 ; if ( startByte < 0 || ( startByte + dataSize) > bitmapByteSize) { std:: cerr << "Invalid start byte position or data size: " << startByte << std:: endl; return - 1 ; } for ( uint32_t i = 0 ; i < dataSize; i++ ) { uint32_t bytePos = startByte + i; data[ i] = this -> data[ bytePos] ; std:: cout << "readData bytePos [" << bytePos << "] data[" << ( int ) data[ i] << "]" << std:: endl; } return 0 ; } int writeData ( uint32_t startByte, const uint8_t * data, uint32_t dataSize) { uint32_t bitmapByteSize = ( size + 7 ) / 8 ; if ( startByte < 0 || ( startByte + dataSize) > bitmapByteSize) { std:: cerr << "Invalid start byte position or data size: " << startByte << std:: endl; return - 1 ; } for ( uint32_t i = 0 ; i < dataSize; i++ ) { uint32_t bytePos = startByte + i; this -> data[ bytePos] = data[ i] ; std:: cout << "writeData bytePos [" << bytePos << "] data[" << ( int ) data[ i] << "]" << std:: endl; } return 0 ; }
} ; int main ( )
{ uint32_t bitmapSize = 32 ; Bitmap bitmap ( bitmapSize) ; bitmap. setBit ( 8 , true ) ; bitmap. setBit ( 9 , true ) ; bitmap. setBit ( 18 , true ) ; bitmap. printBitmap ( ) ; bitmap. setBit ( 18 , false ) ; std:: cout << "Bit 18 is set after clearing: " << bitmap. getBit ( 18 ) << std:: endl; bitmap. printBitmap ( ) ; uint8_t dateRead = 0 ; bitmap. readData ( 1 , & dateRead, sizeof ( dateRead) ) ; std:: cout << "dateRead [" << ( int ) dateRead << "]" << std:: endl; uint8_t dateWrite = 0xFF ; bitmap. writeData ( 0 , & dateWrite, sizeof ( dateWrite) ) ; bitmap. printBitmap ( ) ; return 0 ;
}
test