C Program to Generate Random Hexadecimal Bytes

This C program generates random hexadecimal bytes of arbitrary length. The idea is to genrate decimal number first and convert it to hexadecimal.

Here is the source code of the C program to generate random hexadecimal bytes. The C program is successfully compiled and run on a Linux system. The program output is also shown below.

  1. #include <time.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4.  
  5. int main(void)
  6. {
  7.     int length;
  8.     char str[] = "0123456789ABCDEF";
  9.     /* Seed number for rand() */
  10.     srand((unsigned int) time(0) + getpid());
  11.     length = rand() % 15 + 8;
  12.  
  13.     while(length--) {
  14.         putchar(str[rand() % 16]);
  15.         srand(rand());
  16.     }
  17.     printf("\n");
  18.  
  19.     return EXIT_SUCCESS;
  20. }

$ gcc hexadecimal.c -o hexadecimal
$ ./hexadecimal
 
DE38C3A25D

Sanfoundry Global Education & Learning Series – 1000 C Programs.

advertisement
advertisement

Here’s the list of Best Books in C Programming, Data Structures and Algorithms.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.