Thread: Need help

  1. #1
    Registered User
    Join Date
    Jan 2018
    Posts
    4

    Need help

    I need huge help. How do I Modify the program to print hex instead of binary, without using * printf("%x"). That is, use putchar() to output each hex digit.
    * Note that putchar('0' + 1) outputs the character "1",
    * putchar ('0' + 2) outputs the character "2", etc., and that
    * putchar('a' + 1) outputs the letter "b",
    * putchar('a' + 2) outputs the letter "c", etc.






    Code:
    int main(void) {
        printf("\n");
        print_binary(65535);
        print_binary(1<<31 | 1<<30 | 1<<5 | 1<<0);
        print_binary(-7);
        print_binary(-7.0);
        print_binary("42");
        printf("\n");
        return 0;
    }
    
    
    /*
     * Print num in binary, with leading zeros.
     */
    void print_binary(int num) {
            // The current bit we're sending to output.  Remember,
            // the least significant bit is bit 0.
        int curr_bit_num = (sizeof(int) * 8 - 1);
    
    
        while (curr_bit_num >= 0) {
            int mask = 1 << curr_bit_num;
            int bit = ((mask & num) >> curr_bit_num) & 1;
            putchar('0' + bit);
            if (curr_bit_num > 0 && curr_bit_num % 4 == 0) {
                putchar('_');
            }
            curr_bit_num--;
        }
    
    
        printf("    is binary for %d\n", num);
    }

  2. #2
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Hex digits are 4 bit numbers, your job is to match each 4 bit number to its hex digit, and output a hex number based on an arbitrary set of bits. For example, 0101 is 5, 1110 is e, 0010 is 2 and 1010 is a. Together the set of bits 01011110101001010010 is 0x5ea52.

  3. #3
    Registered User
    Join Date
    Jan 2018
    Posts
    4
    Thank you for the help

Popular pages Recent additions subscribe to a feed

Tags for this Thread