Re: Canonical way / best practice for 128-bit integers

From: Jason Bacon <bacon4000_at_gmail.com>
Date: Sat, 09 Jul 2022 16:56:05 UTC
On 7/9/22 11:26, Marc Veldman wrote:
> Hello,
> 
> I’m working on some bluetooth code, and that involves handling 128-bit uuids.
> There are various ways to handle in the FreeBSD codebase, like in sdp.h:
> 
> /*
>   * SDP int128/uint128 parameter
>   */
>      
> struct int128 {
>          int8_t  b[16];
> };
> typedef struct int128   int128_t;
> typedef struct int128   uint128_t;
> 
> and in sys/dev/random/uint128.h
> 
> #ifdef USE_REAL_UINT128_T
> typedef __uint128_t uint128_t;
> #define UINT128_ZERO 0ULL
> #else
> typedef struct {
>          /* Ignore endianness */
>          uint64_t u128t_word0;
>          uint64_t u128t_word1;
> } uint128_t;
> static const uint128_t very_long_zero = {0UL,0UL};
> #define UINT128_ZERO very_long_zero
> #endif
> 
> Is there any recommended / standard way to handle 128 bit integers in a portable way?
> 
> Best regards,
> 
> Marc Veldman

Have you tried working with __uint128_t?  Support is not complete, e.g. 
in inttypes.h and printf(), but arithmetic works:

NetBSD netbsd9.acadix  bacon ~ 1002: (pkgsrc): cat junk.c
#include <stdio.h>
#include <sysexits.h>

int     main(int argc,char *argv[])

{
     __uint128_t x = 20, y = 30;

     printf("%zu %lu\n", sizeof(x), (unsigned long)(x + y));
     return EX_OK;
}

NetBSD netbsd9.acadix  bacon ~ 1003: (pkgsrc): ./junk
16 50

-- 
Life is a game.  Play hard.  Play fair.  Have fun.