Created
November 22, 2013 17:54
-
-
Save wention/7604101 to your computer and use it in GitHub Desktop.
converte binary to hex,or hex to binary
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
| /* | |
| * create by wention 11,23,2013 | |
| */ | |
| #define NaN 255 | |
| char decode_table[] = "0123456789ABCDEF"; | |
| //char decode_table1[] = "0123456789abcdef"; | |
| unsigned char encode_table[] = {0,1,2,3,4,5,6,7,8,9,NaN,NaN,NaN,NaN,NaN,NaN,NaN,10,11,12,13,14,15}; | |
| void binary_to_hex( unsigned char* binary, //a point of data need to be convert | |
| unsigned long length, //size of binary data | |
| unsigned char* buffer) //a buffer pointer to receive output note that | |
| { // the function does not malloc memory for it | |
| unsigned long k =0; // current buffer writen pointer | |
| for ( unsigned long i =0; i < length; i++) | |
| { | |
| buffer[k++] = decode_table[ binary[i] >> 4]; | |
| buffer[k++] = decode_table[ binary[i] & 0x0F]; | |
| } | |
| } | |
| //////////////////////////////////////////////////////////////////////////////////// | |
| // | |
| // bool hex_to_binary(unsigned char* hex, //a point of data need to be convert | |
| // unsigned long length, //size of data | |
| // unsigned char* buffer) //a buffer pointer to receive output note that | |
| // // the function does not calloc memory for it | |
| bool hex_to_binary(unsigned char* hex, | |
| unsigned long length, | |
| unsigned char* buffer) | |
| { | |
| unsigned long k=0; | |
| if ( ( length%2) ) | |
| return false; | |
| for( unsigned long i =0; i < length/2; i++) | |
| { | |
| unsigned char l = encode_table[ hex[ k++]-0x30] << 4; | |
| unsigned char r = encode_table[ hex[ k++]-0x30]; | |
| buffer[i] = l | r; | |
| } | |
| return true; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment