Convert Decimal & Hex in C: Full Beginner’s Guide

目次

1. Introduction

What Is a Number Base (Radix)

In the world of computers, numbers are represented in various bases (radices). The base we use daily is decimal, but in C programming, hexadecimal, binary, octal, and others are also widely used. Hexadecimal, in particular, appears frequently in memory addresses, bit operations, embedded systems, and color code specifications. For example, the color code “#FFFFFF” is a value expressed in hexadecimal, which converts to “16777215” in decimal. Understanding base conversions accurately is essential when working with C.

Purpose of This Article

This article clearly explains how to convert between decimal and hexadecimal in C. It covers everything from basic concepts to practical sample code, making it suitable for beginners to apply immediately.

2. How to Convert Decimal to Hexadecimal in C

Using the printf Function

In C, you can easily convert a decimal number to hexadecimal and display it by using the printf function.

Basic Example

#include <stdio.h>

int main() {
    int number = 255; // decimal
    printf("%xn", number); // lowercase hexadecimal
    printf("%Xn", number); // uppercase hexadecimal
    return 0;
}

Explanation

  • %x: lowercase hexadecimal representation
  • %X: uppercase hexadecimal representation
For example, when number = 255, the output is as follows.
  • %x: ff
  • %X: FF

How to Pad Digits

By specifying a width in the format specifier, you can display hexadecimal numbers with a fixed number of digits.
#include <stdio.h>

int main() {
    int number = 255;
    printf("%04xn", number); // pad to 4 digits
    return 0;
}
Output: 00ff Adding leading zeros ensures a uniform appearance even when the number has fewer digits.

Using the sprintf Function

Instead of the printf function, you can use the sprintf function to store the conversion result as a string.

Basic Example

#include <stdio.h>

int main() {
    int number = 255;
    char buffer[10];
    sprintf(buffer, "%x", number);
    printf("Hex: %sn", buffer); // output as a string
    return 0;
}

Explanation

Since buffer holds the hexadecimal string, you can reuse it later or pass it to other functions, enabling more flexible programs.

Manual Conversion (Using Bitwise Operations)

This section explains how to manually convert a decimal number to hexadecimal using bitwise operations, which is useful for deepening your understanding of base conversion.

Example Code

#include <stdio.h>
#include <string.h>

int main() {
    int number = 255;
    char hex[10];
    int i = 0;

    while (number > 0) {
        int remainder = number % 16;
        hex[i++] = (remainder < 10) ? '0' + remainder : 'A' + (remainder - 10);
        number /= 16;
    }
    hex[i] = '�';

    // reverse the string
    for (int j = 0; j < i / 2; j++) {
        char temp = hex[j];
        hex[j] = hex[i - j - 1];
        hex[i - j - 1] = temp;
    }

    printf("Hex: %sn", hex);
    return 0;
}

Explanation

  1. Calculate the remainder with number % 16 and convert it to the corresponding hexadecimal character.
  2. Update the quotient with number /= 16 to compute the next digit.
  3. Finally, reverse the string to output the digits in the correct order.
This code demonstrates the basic technique for performing manual base conversion.
年収訴求

3. How to Convert Hexadecimal to Decimal in C

Using the scanf Function

scanf can read hexadecimal values directly as decimal.

Basic Example

#include <stdio.h>

int main() {
    int number;
    printf("Please enter a hexadecimal number: ");
    scanf("%x", &number); // Receive input as hexadecimal
    printf("Decimal: %dn", number); // Display as decimal
    return 0;
}

Explanation

  1. Using the format specifier %x accepts hexadecimal input.
  2. The entered value is converted to decimal and stored in the variable number.
  3. The printf function uses %d to display the decimal value.

Sample Output

Input: FF Output: Decimal: 255

Notes

  • The user must input values in hexadecimal format (e.g., FF, 1A3).
  • Including a leading “0x” is also handled correctly (e.g., 0xFF).

Using the strtol Function

strtol is a convenient function that converts a string to a number with a specified base.

Basic Example

#include <stdio.h>
#include <stdlib.h>

int main() {
    char hexString[] = "FF"; // Hexadecimal string
    long number = strtol(hexString, NULL, 16); // Convert specifying base 16
    printf("Decimal: %ldn", number);
    return 0;
}

Explanation

  1. The first argument of strtol is the string to convert (here hexString).
  2. The second argument is a pointer to the end of the parsed string; since we don’t use it, we pass NULL.
  3. Specifying the base (16 here) as the third argument converts from hexadecimal to decimal.

Sample Output

Input: "FF" Output: Decimal: 255

Using strtol with Error Handling

Example with Error Handling

#include <stdio.h>
#include <stdlib.h>
#include <errno.h>

int main() {
    char hexString[] = "ZZZ"; // Invalid hexadecimal
    char *endptr;
    errno = 0; // Initialize error

    long number = strtol(hexString, &endptr, 16);

    if (errno != 0 || *endptr != '\0') {
        printf("Invalid input.\n");
    } else {
        printf("Decimal: %ldn", number);
    }

    return 0;
}

Explanation

  1. endptr points to the position where conversion stopped. If there are characters that were not converted, *endptr will not be '\0'.
  2. Checking errno can detect overflow and other errors.
  3. If invalid input is detected, an error message is displayed.

Sample Output

Input: "ZZZ" Output: Invalid input.

Manual Conversion Method

Example Code

#include <stdio.h>
#include <string.h>
#include <math.h>

int main() {
    char hexString[] = "FF";
    int length = strlen(hexString);
    int decimal = 0;

    for (int i = 0; i < length; i++) {
        char digit = hexString[i];
        int value;

        if (digit >= '0' && digit <= '9') {
            value = digit - '0';
        } else if (digit >= 'A' && digit <= 'F') {
            value = digit - 'A' + 10;
        } else if (digit >= 'a' && digit <= 'f') {
            value = digit - 'a' + 10;
        } else {
            printf("Invalid character.\n");
            return 1;
        }

        decimal += value * pow(16, length - i - 1);
    }

    printf("Decimal: %dn", decimal);
    return 0;
}

Explanation

  1. Each character is parsed one digit at a time and converted to its decimal value.
  2. Multiply by the positional weight (powers of 16) and sum.

Sample Output

Input: "FF" Output: Decimal: 255

4. Practical Sample Code

Bidirectional Conversion Program

Program Overview

This program allows you to select the following operations.
  1. Convert decimal to hexadecimal
  2. Convert hexadecimal to decimal

Code Example

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

void decimalToHexadecimal() {
    int decimal;
    printf("Please enter a decimal number: ");
    scanf("%d", &decimal);
    printf("Hexadecimal: %Xn", decimal);
}

void hexadecimalToDecimal() {
    char hex[20];
    printf("Please enter a hexadecimal number: ");
    scanf("%s", hex);

    // Validate input string
    for (int i = 0; i < strlen(hex); i++) {
        if (!isxdigit(hex[i])) {
            printf("Invalid hexadecimal number.n");
            return;
        }
    }

    int decimal = (int)strtol(hex, NULL, 16);
    printf("Decimal: %dn", decimal);
}

int main() {
    int choice;

    while (1) {
        printf("nPlease select a conversion option:n");
        printf("1. Convert decimal to hexadecimal n");
        printf("2. Convert hexadecimal to decimal n");
        printf("3. Exit n");
        printf("Selection: ");
        scanf("%d", &choice);

        switch (choice) {
            case 1:
                decimalToHexadecimal();
                break;
            case 2:
                hexadecimalToDecimal();
                break;
            case 3:
                printf("Exiting program.n");
                return 0;
            default:
                printf("Invalid selection. Please try again.n");
        }
    }
    return 0;
}

Execution Example

Case 1: Convert decimal to hexadecimal
Please select a conversion option:
1. Convert decimal to hexadecimal
2. Convert hexadecimal to decimal
3. Exit
Selection: 1
Please enter a decimal number: 255
Hexadecimal: FF
Case 2: Convert hexadecimal to decimal
Please select a conversion option:
1. Convert decimal to hexadecimal
2. Convert hexadecimal to decimal
3. Exit
Selection: 2
Please enter a hexadecimal number: FF
Decimal: 255
Case 3: Invalid hexadecimal input
Please select a conversion option:
1. Convert decimal to hexadecimal
2. Convert hexadecimal to decimal
3. Exit
Selection: 2
Please enter a hexadecimal number: ZZZ
Invalid hexadecimal number.

Error Handling Points

Handling Invalid Input

  1. Check validity of hexadecimal input:
  • Use the isxdigit function to verify each character is a valid hexadecimal digit (0-9, A-F, a-f).
  1. Decimal input error handling:
  • If the input is not numeric, display an error message and prompt for re‑entry.

Preventing Infinite Loops

If the program does not define a clear termination condition, an infinite loop can occur. This program exits correctly when option “3” is selected.

Program Extension Ideas

You can enhance the program by adding the following features.
  1. Conversion to binary or octal
  • Add a menu to select the numeral base.
  1. Specify digit width to format conversion results
  • Add an option to format the output to a fixed width.
  1. Logging to a file
  • Save conversion results to a log file.

Conclusion

This sample program provides a practical example for easily converting between decimal and hexadecimal. It handles user input and includes error handling, making it safe for beginners to use.

5. Caveats and Best Practices

Cautions Regarding the Use of Format Specifiers

Aligned Output with Fixed Width

printf function can be used to output hexadecimal values; by setting the format specifier appropriately, you can align the width and pad with leading zeros.
#include <stdio.h>

int main() {
    int number = 255;
    printf("4-digit hexadecimal: %04X\n", number); // Output: 00FF
    return 0;
}
  • %04X: Outputs a 4-digit uppercase hexadecimal number, padding missing digits with zeros.
  • Using this format ensures aligned and readable output.

Choosing Uppercase or Lowercase

Hexadecimal output can be either uppercase (%X) or lowercase (%x). Choosing between them as needed allows flexible output suited to appearance or purpose.

Validating Input Values

Decimal Input

Because users may enter invalid values, adding error handling improves program reliability.
#include <stdio.h>

int main() {
    int number;
    printf("Please enter a decimal number: ");
    if (scanf("%d", &number) != 1) {
        printf("Invalid input.\n");
        return 1;
    }
    printf("Entered value: %d\n", number);
    return 0;
}

Hexadecimal Input

When receiving a hexadecimal string as input, it is important to verify that the input is valid.
#include <ctype.h>
#include <stdio.h>
#include <string.h>

int isValidHex(const char *hex) {
    for (int i = 0; i < strlen(hex); i++) {
        if (!isxdigit(hex[i])) {
            return 0; // Contains invalid character
        }
    }
    return 1; // Valid hexadecimal
}

int main() {
    char hex[20];
    printf("Please enter a hexadecimal number: ");
    scanf("%s", hex);

    if (!isValidHex(hex)) {
        printf("Invalid hexadecimal number.\n");
        return 1;
    }

    printf("The entered hexadecimal number is valid.\n");
    return 0;
}

Handling Negative Numbers and Overflows

Handling Negative Numbers

When dealing with negative numbers, it depends on signed types (such as int or long). Outputting a negative number in hexadecimal uses the two’s complement representation internally.
#include <stdio.h>

int main() {
    int number = -255;
    printf("Hexadecimal (negative): %X\n", number); // Output is two's complement representation
    return 0;
}

Avoiding Overflows

When handling large values, you need to be careful not to exceed type limits. In C, you can check type ranges using the following headers.
#include <limits.h>
#include <stdio.h>

int main() {
    printf("Maximum int value: %d\n", INT_MAX);
    printf("Minimum int value: %d\n", INT_MIN);
    return 0;
}
By selecting appropriate types, you can reduce the risk of overflow. For example, when dealing with very large values, using the long long type is recommended.

Techniques to Improve Readability and Maintainability

Comments and Naming Conventions

  • Give functions and variables meaningful names and add appropriate comments to improve code readability.

Leveraging Standard Functions

  • Manual base conversion is useful for learning, but in production, prioritizing standard functions (such as printf and strtol) can improve code maintainability.

Testing the Program

Importance of Test Cases

When creating a base conversion program, it is important to test cases such as the following.
  • Valid input (e.g., decimal 255 → hexadecimal FF)
  • Invalid input (e.g., entering string ABC as a decimal)
  • Boundary values (e.g., maximum INT_MAX, minimum INT_MIN)
  • Negative numbers or zero input
Running tests can increase the program’s reliability.

6. FAQ (Frequently Asked Questions)

How to add a leading “0x” to hexadecimal output with printf?

Answer:

To add a leading “0x”, explicitly prepend the string “0x” before the format specifier.

Example code:

#include <stdio.h>

int main() {
    int number = 255;
    printf("Hexadecimal (with 0x): 0x%Xn", number); // Output: 0xFF
    return 0;
}

Note:

“0x” is the standard prefix indicating hexadecimal. It is commonly used, for example, when dealing with color codes or memory addresses.

What happens when you try to convert an invalid string with strtol?

Answer:

strtol does not throw an error even if the string is invalid; it converts only the valid portion. When an unconvertible character is encountered, the rest of the string is ignored.

Example code:

#include <stdio.h>
#include <stdlib.h>

int main() {
    char hexString[] = "FFG12";
    char *endptr;
    long number = strtol(hexString, &endptr, 16);

    printf("Converted value: %ldn", number);
    printf("Unconverted part: %sn", endptr); // Output: G12
    return 0;
}

Sample output:

Converted value: 255
Unconverted part: G12

How to convert a decimal to hexadecimal without using the printf function?

Answer:

You can manually convert using bitwise operations. This approach helps understand the internal logic of base conversion.

Example code:

#include <stdio.h>

void decimalToHex(int decimal) {
    char hex[20];
    int index = 0;

    while (decimal > 0) {
        int remainder = decimal % 16;
        hex[index++] = (remainder < 10) ? '0' + remainder : 'A' + (remainder - 10);
        decimal /= 16;
    }

    printf("Hexadecimal: ");
    for (int i = index - 1; i >= 0; i--) {
        printf("%c", hex[i]);
    }
    printf("n");
}

int main() {
    int number = 255;
    decimalToHex(number);
    return 0;
}

How to limit the number of digits when reading input with scanf?

Answer:

You can limit the input length by specifying a field width in the scanf format specifier.

Example code:

#include <stdio.h>

int main() {
    char hex[5]; // Accept up to 4 digits
    printf("Please enter a hexadecimal number up to 4 digits: ");
    scanf("%4s", hex);
    printf("Entered value: %sn", hex);
    return 0;
}

Note:

The format specifier %4s allows input of a string up to 4 characters.

How to convert to other bases (e.g., binary or octal)?

<h4answer:< h4=””> Using the printf function, you can also convert to other bases. Use the appropriate format specifier or logic depending on the base.

Example code: conversion to binary

#include <stdio.h>

void decimalToBinary(int decimal) {
    char binary[32];
    int index = 0;

    while (decimal > 0) {
        binary[index++] = (decimal % 2) + '0';
        decimal /= 2;
    }

    printf("Binary: ");
    for (int i = index - 1; i >= 0; i--) {
        printf("%c", binary[i]);
    }
    printf("n");
}

int main() {
    int number = 255;
    decimalToBinary(number);
    return 0;
}

How to convert uppercase hexadecimal to lowercase?

Answer:

You can use the tolower function from the C standard library to convert uppercase hexadecimal digits to lowercase.

Example code:

#include <stdio.h>
#include <ctype.h>
#include <string.h>

void toLowercase(char *hex) {
    for (int i = 0; i < strlen(hex); i++) {
        hex[i] = tolower(hex[i]);
    }
}

int main() {
    char hex[] = "FF";
    toLowercase(hex);
    printf("Lowercase hexadecimal: %sn", hex);
    return 0;
}

Sample output:

Lowercase hexadecimal: ff

How to output zero-padded hexadecimal format?

Answer:

You can output zero-padded format by specifying a field width in the printf format specifier.

Example code:

#include <stdio.h>

int main() {
    int number = 15;
    printf("Zero-padded 4-digit hexadecimal: %04Xn", number); // Output: 000F
    return 0;
}

7. Summary

In this article, we comprehensively covered decimal‑to‑hexadecimal and hexadecimal‑to‑decimal conversion using C, from fundamentals to practical sample code, pitfalls, and FAQs. Below, we recap the key points.

Key Points

Fundamental Concepts of Numeral Systems

  • Decimal is the numeric notation we use daily, while hexadecimal is commonly used for specific purposes (e.g., memory addresses or color codes).
  • C provides flexible ways to handle numbers in various bases.

Conversion from Decimal to Hexadecimal

  • You can convert easily and efficiently using the printf or sprintf functions.
  • We also presented a manual conversion method using bitwise operations, which is useful for understanding the conversion logic.

Conversion from Hexadecimal to Decimal

  • You can convert a hexadecimal string to decimal using the scanf or strtol functions.
  • Including handling of invalid input and errors allows you to create more robust programs.

Practical Program Example

  • Through a bidirectional conversion program, we processed user input to achieve decimal‑hexadecimal mutual conversion.
  • We also explained how to incorporate error handling to deal with incorrect input.

Cautions and Best Practices

  • We described how to use format specifiers and choose uppercase or lowercase representations to format the output nicely.
  • We highlighted the importance of handling negative numbers and overflow, and of carefully selecting types and checking ranges.

Frequently Asked Questions (FAQ)

  • We addressed practical questions (e.g., how to prepend “0x” with printf, how to handle invalid input) with concrete examples.
  • We also touched on how to apply these techniques to other bases (binary or octal).

What You’ll Gain from This Article

By reading this article, readers will learn and be able to apply the following.
  1. Fundamental concepts and applications of radix conversion in C
  2. Implementation of base conversion using executable code
  3. Creating robust programs that include input validation and error handling

For Further Learning

To deepen your understanding, we recommend studying the following.
  • Methods for converting to other bases (binary and octal)
  • Implementing radix conversion in programming languages other than C
  • Knowledge related to memory management and binary manipulation
We hope article serves as a practical and valuable guide for beginners learning C and programmers dealing with radix conversion. Use it as a reference and challenge yourself to create more advanced programs.</h4answer:<>

7. Summary

In this article, we comprehensively covered decimal‑to‑hexadecimal and hexadecimal‑to‑decimal conversion using C, from fundamentals to practical sample code, pitfalls, and FAQs. Below, we recap the key points.

Key Points

Fundamental Concepts of Numeral Systems

  • Decimal is the numeric notation we use daily, while hexadecimal is commonly used for specific purposes (e.g., memory addresses or color codes).
  • C provides flexible ways to handle numbers in various bases.

Conversion from Decimal to Hexadecimal

  • You can convert easily and efficiently using the printf or sprintf functions.
  • We also presented a manual conversion method using bitwise operations, which is useful for understanding the conversion logic.

Conversion from Hexadecimal to Decimal

  • You can convert a hexadecimal string to decimal using the scanf or strtol functions.
  • Including handling of invalid input and errors allows you to create more robust programs.

Practical Program Example

  • Through a bidirectional conversion program, we processed user input to achieve decimal‑hexadecimal mutual conversion.
  • We also explained how to incorporate error handling to deal with incorrect input.

Cautions and Best Practices

  • We described how to use format specifiers and choose uppercase or lowercase representations to format the output nicely.
  • We highlighted the importance of handling negative numbers and overflow, and of carefully selecting types and checking ranges.

Frequently Asked Questions (FAQ)

  • We addressed practical questions (e.g., how to prepend “0x” with printf, how to handle invalid input) with concrete examples.
  • We also touched on how to apply these techniques to other bases (binary or octal).

What You’ll Gain from This Article

By reading this article, readers will learn and be able to apply the following.
  1. Fundamental concepts and applications of radix conversion in C
  2. Implementation of base conversion using executable code
  3. Creating robust programs that include input validation and error handling

For Further Learning

To deepen your understanding, we recommend studying the following.
  • Methods for converting to other bases (binary and octal)
  • Implementing radix conversion in programming languages other than C
  • Knowledge related to memory management and binary manipulation
We hope article serves as a practical and valuable guide for beginners learning C and programmers dealing with radix conversion. Use it as a reference and challenge yourself to create more advanced programs.
侍エンジニア塾