Skip to content

Commit

Permalink
Add base::count_bits() function
Browse files Browse the repository at this point in the history
  • Loading branch information
dacap committed Oct 25, 2023
1 parent 58709a0 commit 5214106
Show file tree
Hide file tree
Showing 2 changed files with 73 additions and 0 deletions.
28 changes: 28 additions & 0 deletions base/count_bits.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// LAF Base Library
// Copyright (c) 2023 Igara Studio S.A.
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.

#ifndef BASE_COUNT_BITS_H_INCLUDED
#define BASE_COUNT_BITS_H_INCLUDED
#pragma once

#include <cstddef>
#include <limits>

namespace base {

template<typename T>
constexpr inline size_t count_bits(const T v) {
size_t n = 0;
for (size_t b=0; b<sizeof(T)*8; ++b) {
if (v & (T(1) << b))
++n;
}
return n;
}

}

#endif
45 changes: 45 additions & 0 deletions base/count_bits_tests.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// LAF Base Library
// Copyright (c) 2023 Igara Studio S.A.
//
// This file is released under the terms of the MIT license.
// Read LICENSE.txt for more information.

#include <gtest/gtest.h>

#include "base/ints.h"
#include "base/count_bits.h"

using namespace base;

TEST(CountBits, CommonCases)
{
EXPECT_EQ(0, count_bits(0));
EXPECT_EQ(1, count_bits(1));
EXPECT_EQ(1, count_bits(2));
EXPECT_EQ(2, count_bits(3));
}

TEST(CountBits, Limits)
{
EXPECT_EQ(32, count_bits(0xffffffff));
EXPECT_EQ(64, count_bits(0xffffffffffffffffll));
}

TEST(CountBits, UnsignedLong)
{
EXPECT_EQ(1, count_bits<unsigned long>(1));
EXPECT_EQ(10, count_bits<unsigned long>(1023));
}

TEST(CountBits, Rgb30bpp)
{
EXPECT_EQ(10, count_bits<unsigned long>(0x3ff));
EXPECT_EQ(10, count_bits<unsigned long>(0xffc00));
EXPECT_EQ(10, count_bits<unsigned long>(0x3ff00000));
}

int main(int argc, char** argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

0 comments on commit 5214106

Please sign in to comment.