Last active
October 19, 2015 16:52
-
-
Save mpenick/90fde41a4ef6b468b77c to your computer and use it in GitHub Desktop.
This file contains hidden or 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 <stdbool.h> | |
| #include <stdio.h> | |
| #include <stdint.h> | |
| int invalid_compare(uint32_t a, uint32_t b) { | |
| // Note: Conversion from unsigned to signed int. This will fail for any | |
| // spread of a - b that's greater than INT32_MAX. | |
| return a - b; | |
| } | |
| uint32_t from_string(const char* addr) { | |
| uint8_t a = 0, b = 0, c = 0, d = 0; | |
| sscanf(addr, "%hhu. %hhu.%hhu.%hhu", &a, &b, &c, &d); | |
| return (a << 24) | (b << 16) | (c << 8) | d; | |
| } | |
| bool is_fail(const char* addr1, const char * addr2) { | |
| uint32_t a = from_string(addr1); | |
| uint32_t b = from_string(addr2); | |
| return (a > b && invalid_compare(a, b) <= 0) || (a < b && invalid_compare(a, b) >= 0); | |
| } | |
| void test_compare(const char* addr1, const char * addr2) { | |
| printf("%16s <=> %16s (%s)\n", addr1, addr2, is_fail(addr1, addr2) ? "fail" : "success"); | |
| } | |
| int main() { | |
| test_compare("10.10.10.10", "10.10.10.9"); | |
| test_compare("10.10.10.9", "10.10.10.10"); | |
| test_compare("190.0.0.0", "10.0.0.0"); | |
| test_compare("10.0.0.0", "190.0.0.0"); | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment