1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- #include<stdlib.h>
- #include<string.h>
- #include<stdio.h>
- int hex2char(int c);
- void file_print(char* s, FILE* f);
- void require(int bool, char* error);
- char* number_to_hex(int a, int bytes)
- {
- require(bytes > 0, "number to hex must have a positive number of bytes greater than zero\n");
- char* result = calloc(1 + (bytes << 1), sizeof(char));
- if(NULL == result)
- {
- file_print("calloc failed in number_to_hex\n", stderr);
- exit(EXIT_FAILURE);
- }
- int i = 0;
- int divisor = (bytes << 3);
- require(divisor > 0, "unexpected wrap around in number_to_hex\n");
-
- while(0 != divisor)
- {
- divisor = divisor - 4;
- result[i] = hex2char((a >> divisor) & 0xF);
- i = i + 1;
- }
- return result;
- }
|