Created
May 7, 2016 00:16
-
-
Save nfarring/b11dde6ada832cad4d606ff1d8ae6691 to your computer and use it in GitHub Desktop.
Overloading C++ operator<< to accept an __int128 from GCC/Clang
This file contains hidden or 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
/** | |
* @file | |
*/ | |
#include "int128.h" | |
/* | |
* http://stackoverflow.com/a/25115163 | |
*/ | |
std::ostream& operator<<(std::ostream& os, const __int128 i) noexcept | |
{ | |
std::ostream::sentry s(os); | |
if (s) { | |
unsigned __int128 tmp = i < 0 ? -i : i; | |
char buffer[128]; | |
char *d = std::end(buffer); | |
do { | |
--d; | |
*d = "0123456789"[tmp % 10]; | |
tmp /= 10; | |
} while (tmp != 0); | |
if (i < 0) { | |
--d; | |
*d = '-'; | |
} | |
int len = std::end(buffer) - d; | |
if (os.rdbuf()->sputn(d, len) != len) { | |
os.setstate(std::ios_base::badbit); | |
} | |
} | |
return os; | |
} |
This file contains hidden or 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
/** | |
* @file | |
* | |
* Support for 128-bit integers in GCC and Clang. | |
*/ | |
#ifndef __INT128_H__ | |
#define __INT128_H__ | |
/* | |
* Standard | |
*/ | |
#include <iostream> | |
/** | |
* Overload the ostream operator << to support 128-bit integers. | |
*/ | |
std::ostream& | |
operator<<( std::ostream& dest, const __int128 value ) | |
noexcept; | |
#endif /* __INT128_H__ */ |
This file contains hidden or 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
/** | |
* @file | |
*/ | |
/* | |
* Catch | |
*/ | |
#include <catch.hpp> | |
#include "int128.h" | |
TEST_CASE( "std::ostream::operator<<", "[int128]" ) { | |
__int128 INTEGERS[] = {0, -1, 1, 1234567890}; | |
std::string STRINGS[] = {"0", "-1", "1", "1234567890"}; | |
for (size_t i = 0; i < sizeof(INTEGERS)/sizeof(INTEGERS[0]); i++) { | |
std::stringstream ss; | |
ss << INTEGERS[i]; | |
CHECK(ss.str() == STRINGS[i]); | |
} | |
} | |
TEST_CASE( "<=>", "[int128]" ) { | |
__int128 a = 5; | |
__int128 b = 7; | |
bool test1 = (a < b); | |
bool test2 = (b > a); | |
REQUIRE(test1); | |
REQUIRE(test2); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment