Skip to content

Instantly share code, notes, and snippets.

@ian-abbott
ian-abbott / intwidth.c
Created June 12, 2024 12:00
Show widths of standard integer types when C23 x_WIDTH macros not available
#include <limits.h>
#include <stdint.h>
/* Number of bits in inttype_MAX, or in any (1<<k)-1 where 0 <= k < 2040 */
/* (Attributed to Hallvard B. Furuseth.) */
#define IMAX_BITS(m) ((m)/((m)%255+1) / 255%255*8 + 7-86/((m)%255+12))
/* Helper macros. */
#define MY___WIDTH(x) IMAX_BITS(x##_MAX)
#define MY__U__WIDTH(x) MY___WIDTH(U##x)
@ian-abbott
ian-abbott / heapsort.c
Created September 17, 2021 11:19
heapsort in C with interface like `qsort` in the standard library
#include <stddef.h>
#include "heapsort.h"
static void swapmem(void * restrict a, void * restrict b, size_t size)
{
char *x = a;
char *y = b;
char t;
while (size--) {
@ian-abbott
ian-abbott / binomial.c
Created September 16, 2020 15:20
Binomial coefficient of two unsigned long long values avoiding overflow if possible
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <limits.h>
/**
* \brief Returns Greatest Common Divisor of two unsigned long long values.
*
* \param[in] a First value.
* \param[in] b Second value.
@ian-abbott
ian-abbott / birthdays.cpp
Last active December 6, 2018 16:47
Determines the probability that at least 'N' people in a group of 'M' people share the same birthday.
#include <iostream>
#include <string>
#include <gmpxx.h>
static mpz_class falling_fac(unsigned long n, unsigned long k)
{
mpz_class result = 1;
if (k > n) {
k = n;
@ian-abbott
ian-abbott / ntstatuserror.c
Last active December 19, 2022 13:16
C function to convert an NTSTATUS code into a Win32 error code - alternative to RtlNtStatusToDosError()
#include <windows.h>
/*
* This is an alternative to the RtlNtStatusToDosError()
* function in ntdll.dll. It uses the GetOverlappedResult()
* function in kernel32.dll to do the conversion.
*/
DWORD
ConvertNtStatusToWin32Error(LONG ntstatus)
{