-
-
Notifications
You must be signed in to change notification settings - Fork 138
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
3 changed files
with
30 additions
and
27 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
25 changes: 0 additions & 25 deletions
25
snippets/cpp/math-and-numbers/binary-to-decimal-conversion.md
This file was deleted.
Oops, something went wrong.
26 changes: 26 additions & 0 deletions
26
snippets/cpp/math-and-numbers/binary-to-unsigned-integer-conversion.md
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,26 @@ | ||
--- | ||
title: Binary to Unsigned Integer Conversion | ||
description: Converts a binary number represented as a string to its decimal equivalent. | ||
tags: binary, conversion, c++20 | ||
author: ashukr07 | ||
contributor: majvax | ||
--- | ||
|
||
```cpp | ||
#include <string> | ||
#include <bitset> | ||
#include <stdexcept> | ||
|
||
template <std::unsigned_integral T> | ||
T binary_to_uintegral(const std::string& binary) { | ||
if (binary.size() > sizeof(T) * 8) | ||
throw std::invalid_argument("binary string is too long"); | ||
return static_cast<T>(std::bitset<sizeof(T) * 8>(binary).to_ullong()); | ||
} | ||
|
||
// Usage: | ||
std::string binary(64, '1'); // Binary 8 bytes long with all bits set to 1 | ||
binary_to_uintegral<unsigned long long>(binary); // Returns: 18446744073709551615 | ||
binary_to_uintegral<long long>(binary); // Compiles error: signed/unsigned mismatch | ||
binary_to_uintegral<unsigned long long>(std::string(65, '1')); // Throws: std::invalid_argument | ||
``` |