Home > Software engineering >  Output 128 bit integer using stream operator
Output 128 bit integer using stream operator

Time:12-09

I'm using GCC's 128 bit integer:

__extension__ using uint128_t = unsigned __int128;
uint128_t a = 545;
std::cout << a << std::endl;

However, if I try to output using the stream operator I get the compiler error:

error: ambiguous overload for ‘operator<<’ (operand types are ‘std::ostream’ {aka ‘std::basic_ostream<char>’} and ‘uint128_t’ {aka ‘__int128 unsigned’})

Is there a way to allow this?

Linux, GCC version 11.1, x86-64

CodePudding user response:

libstdc does not have an ostream overload for __int128. However, you can use C 20 <format> library, which supports __int128 formatting in both libstdc and libc .

#include <format>
#include <iostream>

int main() {
  __extension__ using uint128_t = unsigned __int128;
  uint128_t a = 545;
  std::cout << std::format("{}\n", a);
}

Demo

CodePudding user response:

You will have to overload the << operator yourself because std::ostream doesn't have an overload for that type as it is from an external lib. This could help.

  • Related