Last active
December 23, 2015 03:39
-
-
Save LBijaminas/6575272 to your computer and use it in GitHub Desktop.
C function to convert hexadecimal number to string. I was looking for it for the kernel I'm trying to make but couldn't find it, so wrote one myself. Hope this helps somebody.
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
| char checkTheBits(unsigned char hByte); | |
| char* hex_to_string(unsigned int n){ | |
| // output hexadecimal chars | |
| unsigned char* location = &n; //get the location of the hex number | |
| char value[9] = {0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0}; // init null byte array | |
| // array has 9 values, because last one reserved fur null terminator | |
| unsigned char temp_char_l, temp_char_h; // temporary vars | |
| int i = 0, j = 7; // start at 7, because tested on little endian machine | |
| while(location[i]){ | |
| // get lower 4 bits | |
| temp_char_l = location[i] & 0x0f; | |
| if(!(value[j--] = checkTheBits(temp_char_l))) break; // shouldn't happen if hex number given | |
| // get upper 4 bits | |
| temp_char_h = location[i++] >> 4; | |
| if(!(value[j--] = checkTheBits(temp_char_h))) break; // shouldn't happen if hex number given | |
| if ( i == 4 || j <= 0) break; | |
| } | |
| // readjust the array, since we start at the end of the array because of the endianness | |
| j = 0; | |
| while(!j){ | |
| if (!value[j]){ | |
| for(i = 0; i < 8; i++){ | |
| value[i] = value[i+1]; | |
| } | |
| } else { break;} | |
| } | |
| return value; | |
| } | |
| char checkTheBits(u8int hByte){ | |
| /* | |
| Might not be the most efficient algorithm to find the hex | |
| value, but that's the way I thought to do it | |
| */ | |
| // check and print the half byte value | |
| switch(bit){ | |
| case 0x01: | |
| return '1'; | |
| case 0x02: | |
| return '2'; | |
| case 0x03: | |
| return '3'; | |
| case 0x04: | |
| return '4'; | |
| case 0x05: | |
| return '5'; | |
| case 0x06: | |
| return '6'; | |
| case 0x07: | |
| return '7'; | |
| case 0x08: | |
| return '8'; | |
| case 0x09: | |
| return '9'; | |
| case 0x0A: | |
| return 'A'; | |
| case 0x0B: | |
| return 'B'; | |
| case 0x0C: | |
| return 'C'; | |
| case 0x0D: | |
| return 'D'; | |
| case 0x0E: | |
| return 'E'; | |
| case 0x0F: | |
| return 'F'; | |
| case 0x00: | |
| return '0'; | |
| default: | |
| // should never happen | |
| return 0; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment