How to generate random hexadecimal number in C

2 Answers

0 votes
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h> 
#include <time.h>
 
int getRandom(int lower, int upper) { 
    return rand() % (upper - lower + 1) + lower; 
} 
  
int main(void) {
    char s[] = "0123456789ABCDEF";
 
    srand((unsigned int) time(0) + getpid());
 
    int length = getRandom(4, 8);
 
    while(length--) {
        putchar(s[rand() % 16]);
        srand(rand());
 
    }

    return 0;
}
 
    
    
    
/*
run :
    
3FFE
    
*/

 



answered Feb 15, 2021 by avibootz
edited Sep 16, 2025 by avibootz
0 votes
#include <stdio.h>
#include <stdlib.h> 
#include <unistd.h> 
#include <time.h>

int generat_hexadecimal() { 
    int hex = rand() & 0xff;
    
    hex |= (rand() & 0xff) << 8;
    hex |= (rand() & 0xff) << 16;
    hex |= (rand() & 0xff) << 24;

    return hex;
} 
 
int main(void) {
    srand((unsigned int) time(0) + getpid());

    printf("%x\n", generat_hexadecimal());

    return 0;
}

   
   
   
/*
run :
   
f1e2ca7f
   
*/

 



answered Feb 15, 2021 by avibootz

Related questions

1 answer 127 views
1 answer 145 views
1 answer 171 views
1 answer 163 views
...