Generate Random Hex Number: How to Do It

How-to basics · Updated November 23, 2026

To generate a random hex number, use a random number generator that outputs in base-16, or convert a random decimal/byte value to hex; for example, in Python, secrets.token_hex(4) returns a random 8-character hex string. This article explains the methods, tools, and pitfalls of generating random hexadecimal values for programming, security, and design.

What Is a Hex Number and Why Generate One?

Hexadecimal (hex) is a base-16 numeral system using digits 0-9 and letters A-F. Each hex digit represents 4 bits, making it a compact way to express binary data. You might need a random hex number for:

  • Creating unique identifiers (e.g., MongoDB ObjectIDs, UUIDs in hex form)
  • Generating color codes in web design (e.g., #FF5733)
  • Producing cryptographic keys or tokens (though these usually use secure random sources)
  • Testing software that parses hex input

Randomness in hex is just randomness in binary, displayed differently. The core challenge is ensuring the source of randomness is appropriate for your use case—cryptographic versus non-cryptographic.

How to Generate a Random Hex Number in Code

Most programming languages have built-in random functions, but they vary in security and ease of hex output. Here are common examples:

  • Python: secrets.token_hex(n) returns a hex string with 2n characters (cryptographically secure). For non-secure, random.getrandbits(k) then format with format(value, 'x').
  • JavaScript (Node.js): crypto.randomBytes(n).toString('hex') for secure; Math.random().toString(16).slice(2) for a quick non-secure fraction.
  • Java: SecureRandom class, then String.format("%02x", byte) for each byte.
  • Bash: openssl rand -hex 4 outputs 8 hex characters.

For example, in Python, to get a random 4-byte hex (8 characters):

import secrets
print(secrets.token_hex(4))  # e.g., '3f2a9c1b'

If you need a specific length in hex digits, generate enough bytes: each byte yields 2 hex digits, so for N hex digits, generate ceil(N/2) bytes and trim if necessary.

Using Online Random Hex Generators

Many websites offer free random hex generators. They typically let you specify the number of digits or bytes, and some allow output as a string or with a ‘#’ prefix for colors. While convenient, be cautious:

  • For non-critical tasks like picking a random color, online tools are fine.
  • For security-sensitive uses (passwords, tokens), avoid online generators because you cannot verify they use secure randomness or that the output isn’t logged.

If you use an online tool, check if the site uses HTTPS and states its randomness source. For anything important, generate locally.

Generating Random Hex Colors for Web Design

A common need is a random hex color code. A hex color is 6 digits (3 bytes) representing red, green, and blue. To generate one in JavaScript:

function randomColor() {
  return '#' + Math.floor(Math.random()*16777215).toString(16).padStart(6, '0');
}

Note: Math.random() is not cryptographically secure, but for design it’s fine. Ensure the result is always 6 digits by padding with zeros. Some developers mistakenly use Math.random().toString(16).slice(2, 8), which can produce fewer than 6 characters—a common bug. Always pad.

Ensuring True Randomness: Security Considerations

If your random hex number is used for security—like generating an API key, a password reset token, or a session ID—you must use a cryptographically secure random number generator (CSPRNG). Non-secure generators like Math.random() in JavaScript or random.random() in Python are predictable and can be exploited.

Examples of secure sources:

  • Python: secrets module
  • Node.js: crypto.randomBytes()
  • Java: SecureRandom
  • Bash: /dev/urandom or openssl rand

Never use a non-secure PRNG for tokens, passwords, or any value that an attacker could guess to gain access. Also, be aware that generating a hex number from a random integer may have modulo bias if you use modulo to constrain the range—use byte-based generation instead.

Converting Between Decimal, Binary, and Hex

Sometimes you have a random decimal number and need hex, or vice versa. Conversion is straightforward:

  • Decimal to hex: In Python, hex(255) gives ‘0xff’. In JavaScript, (255).toString(16) gives ‘ff’.
  • Hex to decimal: In Python, int('ff', 16) gives 255. In JavaScript, parseInt('ff', 16) gives 255.
  • Binary to hex: Group bits in fours from the right, then map each group to a hex digit. For example, binary 1111 1010 = FA.

Remember that hex is case-insensitive, but by convention uppercase is often used for readability. When storing, be consistent.

Common Pitfalls and How to Avoid Them

  • Incorrect length: If you ask for 4 hex digits but generate 2 bytes, you get 4 digits—good. But if you generate a random integer and then convert, you might get fewer digits than expected. Always pad with leading zeros.
  • Using non-secure RNG for security: As mentioned, never use Math.random() for tokens.
  • Modulo bias: If you generate a random number and then take modulo 16 to get a hex digit, the distribution may be slightly skewed unless the random range is a multiple of 16. Use byte-based methods instead.
  • Forgetting the ‘0x’ prefix: Sometimes you need the prefix for programming languages; sometimes not. Know your context.

To avoid these, prefer language-specific secure random byte functions and format them as hex.

Frequently Asked Questions

How do I generate a random hex number in Excel?

Excel doesn’t have a direct hex random function, but you can use DEC2HEX(RANDBETWEEN(0, 65535), 4) to get a random 4-digit hex number. For more digits, increase the range: DEC2HEX(RANDBETWEEN(0, 16777215), 6) gives a 6-digit hex. Note that RANDBETWEEN recalculates each time the sheet changes; to keep a static value, copy and paste as values.

What is the difference between a random hex number and a UUID?

A UUID (Universally Unique Identifier) is a 128-bit number typically displayed as 32 hex digits in a specific format (e.g., 8-4-4-4-12). A random hex number can be any length. UUIDs are designed to be unique across space and time, often using random bits plus version/variant info. If you need a unique identifier, use a proper UUID generator rather than a random hex string, because UUIDs have a lower collision probability and standard format.

Can I generate a random hex number with a fixed number of digits?

Yes. Determine the number of hex digits you need, then generate enough random bytes. For N hex digits, generate Math.ceil(N/2) bytes, convert to hex, and take the last N characters (or pad with leading zeros if the first byte is small). For example, in Python: secrets.token_hex(4)[:8] gives exactly 8 hex digits.

Is there a way to generate a random hex number without programming?

Yes, you can use online generators, or even a physical method: roll a 16-sided die for each hex digit. For a 6-digit color, roll six times and map 10-15 to A-F. This is truly random if the die is fair, but cumbersome for long numbers.

Why does my random hex sometimes have fewer digits than expected?

This happens when you convert a random integer to hex and the integer is small. For example, Math.random().toString(16).slice(2) can yield a string of variable length. Always pad with leading zeros to the desired length. In JavaScript, use .padStart(length, '0').

Related

Try it: the Date Difference Calculator: days, months, years and weekdays between two dates, with the DATEDIF formulas.

More in How-to basics

Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources

Spotted an error in this guide? Let us know.