Skip to content

Instantly share code, notes, and snippets.

@EdgeCaseBerg
Created July 6, 2013 05:34
Show Gist options
  • Save EdgeCaseBerg/5938780 to your computer and use it in GitHub Desktop.
Save EdgeCaseBerg/5938780 to your computer and use it in GitHub Desktop.
Messing around with a fun fact. Since unsigned integers wrap around, you are able to do modulo arithmetic implicitly for common sizes of 2^n, where n =128 (signed chars), 256 (unsigned chars), 65536 ( short int), and etc for long doubles and other types.
#include <stdio.h>
/*
Fun Fact:
Using an unsigned integer causes integer arithmetic module 2^n where n is the number of bits in the type
*/
main(){
unsigned char mod256;
mod256 = 16*18;
//Generates a warning:
//warning: large integer implicitly truncated to unsigned type [-Woverflow]
//16*18 = 288
//16*18 % 256 == 32
printf("16*18 mod 256 = %d\n", mod256);
unsigned short int mod65536;
//A useful thing to do is work in 16 bit archectures. And to remember you're working modulo
//2^16 + 1 == 1
mod65536 = 16*16*16*16+1;
printf("2^16 + 1 mod 2^16 = %d\n", mod65536);
//Dirty way of computing the max size of an unsigned integer
unsigned long int howBigsALong;
howBigsALong = -1;
printf("An unsigned long can be %lu large\n", howBigsALong);
//Using howBigsALong to determine the power of two representation
int i;
for(i = 0; howBigsALong != 0; i++){
howBigsALong = howBigsALong/2;
}
printf("A long is (2^%d)-1 big\n", i );
//how big is a really long long?
unsigned long long int biglon;
biglon = -1;
unsigned long long int low;
unsigned long long int high;
low = biglon;
high = (biglon >> 64);
//Print in hex because otherwise things get cimplicated
printf("This long is pretty big, its: 0x%llx%llx big! \n", high,biglon);
//and in 2^n
for(i=0; biglon != 0; i++){
biglon = biglon/2;
}
printf(" or (2^%d)-1\n",i*2);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment