/* hex2.c convert number to hexadecimal string * Author: Lin Jensen * Date: 2 February 2016 (Groundhog Day) * * Example of using shift and bitwise logic instructions * * This program divides 32 bits into 8 4-bit nibbles, then calls a function * to convert each nibble to a corresponding character * it fills a string "backwards" to form the usual representation of a number * * See also hex.a by John Waldron, which goes left to right * hex1.a by Lin, which goes right to left, like this one * C operators bitwise logical * and & && * or | || * not ~ ! * xor ^ (none) * shift << (left), >> (right) */ #include /* function to make (rightmost) 4 bits of a 32-bit integer * into an ascii character which represents it as a hexadecimal digit * example: 1011 becomes 'B' or 01000010 * */ char bin2hc( int number) { char hex; hex = number & 0xf; // isolate rightmost 4 bits (nibble) hex = hex | 0x30; // make into ascii code for a digit if (hex > '9') // but if over '9' skip hex =hex + 7; // the 7 chars between 9 and A return hex; } int main() { char digits[9] = " "; // fill with "hex" characters int num, count; printf("Type a number: "); scanf ("%d", &num); // get user input as a number, typed in base 10 count = 8; // do loop for 8 nibbles while (count--) { digits[count] = bin2hc(num); // store character representation num = num >> 4; // shift right 4 bits to move } // all nibbles to the right printf ("In hex this is %s\n", digits); // print resulting string return 0; }