Logo
~Apps~
~Projects~
~Contact~


bitmap_t.cpp

Go to the documentation of this file.
00001 
00006 /*
00007 Copyright (C) 2005  Anders Hedstrom
00008 
00009 This program is free software; you can redistribute it and/or
00010 modify it under the terms of the GNU General Public License
00011 as published by the Free Software Foundation; either version 2
00012 of the License, or (at your option) any later version.
00013 
00014 This program is distributed in the hope that it will be useful,
00015 but WITHOUT ANY WARRANTY; without even the implied warranty of
00016 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00017 GNU General Public License for more details.
00018 
00019 You should have received a copy of the GNU General Public License
00020 along with this program; if not, write to the Free Software
00021 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
00022 */
00023 #include <stdio.h>
00024 
00025 #include "bitmap_t.h"
00026 
00027 
00028 
00029 
00030 bitmap_t::bitmap_t(size_t number_of_pieces)
00031 :m_bitmap(NULL)
00032 ,m_bitmap_size(0)
00033 ,m_number_of_pieces(number_of_pieces)
00034 {
00035         m_bitmap_size = number_of_pieces / 8;
00036         if (number_of_pieces % 8)
00037                 m_bitmap_size++;
00038         m_bitmap = new unsigned char[m_bitmap_size];
00039         memset(m_bitmap, 0, m_bitmap_size);
00040 }
00041 
00042 
00043 bitmap_t::~bitmap_t()
00044 {
00045         if (m_bitmap)
00046                 delete[] m_bitmap;
00047 }
00048 
00049 
00050 void bitmap_t::set(size_t piece)
00051 {
00052         size_t n = piece / 8;
00053         int bit[] = {128,64,32,16,8,4,2,1};
00054         m_bitmap[n] |= bit[piece % 8];
00055 }
00056 
00057 
00058 void bitmap_t::Load(const std::string& filename)
00059 {
00060         FILE *fil = fopen(filename.c_str(), "rb");
00061         if (fil)
00062         {
00063                 fread(m_bitmap, 1, m_bitmap_size, fil);
00064                 fclose(fil);
00065         }
00066 }
00067 
00068 
00069 void bitmap_t::Save(const std::string& filename)
00070 {
00071         FILE *fil = fopen(filename.c_str(), "wb");
00072         if (fil)
00073         {
00074                 fwrite(m_bitmap, 1, m_bitmap_size, fil);
00075                 fclose(fil);
00076         }
00077 }
00078 
00079 
00080 bool bitmap_t::IsSet(size_t piece)
00081 {
00082         size_t n = piece / 8;
00083         int bit[] = {128,64,32,16,8,4,2,1};
00084         return (m_bitmap[n] & bit[piece % 8]) ? true : false;
00085 }
00086 
00087 
00088 size_t bitmap_t::GetSet()
00089 {
00090         size_t q = 0;
00091         for (size_t i = 0; i < m_number_of_pieces; i++)
00092                 if (IsSet(i))
00093                         q++;
00094         return q;
00095 }
00096 
00097 
Page, code, and content Copyright (C) 2006 by Anders Hedström
Generated on Mon Aug 29 20:21:47 2005 for C++ Sockets by  doxygen 1.4.4