Created
December 7, 2017 15:35
-
-
Save AhiyaHiya/99a24ed8ee01e17ad1303d1818dc9e5d to your computer and use it in GitHub Desktop.
Detecting byte order for cases where you need to know. Originally in Obj-C, adapted from iOS macOS Network Cookbook available on Safaribooks.com
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
| typedef enum { | |
| ET_Unknown, | |
| ET_Little, | |
| ET_Big | |
| } endian_type_e; | |
| endian_type_e byte_order() | |
| { | |
| union { | |
| short num_as_short; | |
| char num_as_char[sizeof(short)]; | |
| } test; | |
| test.num_as_short = 0x0102; | |
| if (sizeof(short) == 2) { | |
| if (test.num_as_char[0] == 1 && test.num_as_char[1] == 2) { | |
| return ET_Big; | |
| } | |
| else if (test.num_as_char[0] == 2 && test.num_as_char[1] == 1) { | |
| return ET_Little; | |
| } | |
| else { | |
| return ET_Unknown; | |
| } | |
| } | |
| else | |
| return ET_Unknown; | |
| } | |
| int main(int argc, const char* argv[]) | |
| { | |
| const endian_type_e et = byte_order(); | |
| (void)et; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment