Last active
December 22, 2017 22:52
-
-
Save deeptir18/8191624dd0bec3ad0d2b7eea6ed0c9a9 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdint.h> | |
#define u32 uint32_t | |
// raw difference wrap around from left -> right | |
// on a number line, if I can go in one direction (towards positive), how many steps from left -> right | |
uint32_t dif32(uint32_t left, uint32_t right) { | |
uint32_t max32 = ((uint32_t )~0U); | |
if ( right > left ) { | |
return (right-left); | |
} | |
return (max32 - left) + right; | |
} | |
/* must handle integer wraparound*/ | |
uint64_t mymax64_wrap(uint64_t a, uint64_t b) { | |
uint32_t a32 = (uint32_t)a; | |
uint32_t b32 = (uint32_t)b; | |
uint32_t left_to_right = dif32(a32, b32); // raw dif from a to b | |
uint32_t right_to_left = dif32(b32, a32); // raw dif from b to a | |
// less steps from b to a then a to b -> so order must be (b,a) | |
if ( right_to_left < left_to_right ) { | |
return (uint64_t)a32; | |
} | |
// less steps from a to b then b to a -> so order must be (a,b) | |
return (uint64_t)b32; | |
} | |
int main() | |
{ | |
uint64_t a; | |
uint64_t b; | |
uint64_t max32 = (uint64_t)((uint32_t )~0U); | |
uint64_t max_sub_4 = max32 - 4; | |
printf("Hello World\n"); | |
// test 1: | |
a = 10; | |
b = 6; | |
printf("TEST 1\n"); | |
printf("a: %llu, b:%llu, max: %llu\n", a, b, mymax64_wrap(a, b)); | |
a = 6; | |
b = 10; | |
printf("TEST 2\n"); | |
printf("a: %llu, b:%llu, max: %llu\n", a, b, mymax64_wrap(a, b)); | |
a = max_sub_4; | |
b = 10; | |
printf("TEST 3\n"); | |
printf("a: %llu, b:%llu, max: %llu\n", a, b, mymax64_wrap(a, b)); | |
b = max_sub_4; | |
a = 10; | |
printf("TEST 3\n"); | |
printf("a: %llu, b:%llu, max: %llu\n", a, b, mymax64_wrap(a, b)); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment