-
Notifications
You must be signed in to change notification settings - Fork 64
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
Showing
2 changed files
with
73 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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(); | ||
} |