Skip to content

Instantly share code, notes, and snippets.

@hamsham
Created May 10, 2016 06:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hamsham/596d4bb206387d874b36f668818e6650 to your computer and use it in GitHub Desktop.
Save hamsham/596d4bb206387d874b36f668818e6650 to your computer and use it in GitHub Desktop.
Get the next multiple of an unsigned integer to assist with memory allocations and data alignment.
/**
* Simple program to find the next multiple of a number (AMD, NVIDIA, & Intel share 16-byte alignments for cache lines).
*
* gcc -std=c11 -Wall -Wextra -Werror -pedantic-errors align_nums.c -o align_nums
*/
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
static inline bool is_aligned(const unsigned num, const unsigned alignment)
{
return num % alignment == 0;
}
static inline unsigned next_multiple(const unsigned num, const unsigned alignment)
{
return (num | (alignment-1)) + 1;
}
/*
static inline unsigned next_multiple_4(const unsigned num) {return (num | 0x03) + 1;}
static inline unsigned next_multiple_8(const unsigned num) {return (num | 0x07) + 1;}
static inline unsigned next_multiple_16(const unsigned num) {return (num | 0x0F) + 1;}
static inline unsigned next_multiple_32(const unsigned num) {return (num | 0x1F) + 1;}
static inline unsigned next_multiple_64(const unsigned num) {return (num | 0x3F) + 1;}
static inline unsigned next_multiple_128(const unsigned num) {return (num | 0x7F) + 1;}
static inline unsigned next_multiple_256(const unsigned num) {return (num | 0xFF) + 1;}
*/
int main()
{
const unsigned ideal = 32;
const unsigned maxNums = 20;
unsigned randNums[maxNums];
srand(time(NULL));
printf("Generating random numbers... ");
for (unsigned i = 0; i < maxNums; ++i)
{
randNums[i] = rand() % 513;
}
randNums[0] = ideal;
printf("Done.\n");
printf("Checking alignment of random numbers...\n");
for (unsigned i = 0; i < maxNums; ++i)
{
const unsigned currentNum = randNums[i];
printf("Validating alignment of %u: ", currentNum);
if (!is_aligned(currentNum, ideal))
{
printf("Fail. Nearest Alignment is %u.\n", next_multiple(currentNum, ideal));
}
else
{
printf("Pass.\n");
}
}
printf("Done.\n");
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment