用c写一个函数,生成256位、64位、42位、16位四个16进制随机数的函数并且不使用printf,并且调用他们
时间: 2023-11-28 11:48:24 浏览: 82
下面是一个生成指定位数的随机数的函数,其中使用了rand()函数来生成随机数,利用sprintf()函数将随机数格式化为16进制字符串。
```c
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
void gen_hex(int bit)
{
char hex[bit/4+1];
int i;
for(i=0; i<bit/4; i++)
sprintf(hex+i, "%01x", rand()%16);
hex[bit/4] = '\0';
printf("%s\n", hex);
}
int main()
{
srand((unsigned)time(NULL));
gen_hex(256);
gen_hex(64);
gen_hex(42);
gen_hex(16);
return 0;
}
```
其中,srand()函数用来设置rand()函数的种子,可以让每次运行程序产生不同的随机数序列。在这里我们以当前时间作为种子。
调用gen_hex()函数,传入指定的位数,即可生成相应位数的随机数,并输出到控制台。
相关问题
用c语言写一个 256位16进制的随机数函数
以下是一个用C语言实现的生成256位16进制随机数的函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void generate_random_hex(unsigned char *buf, size_t size) {
// 用时间作为随机数发生器的种子
srand((unsigned int)time(NULL));
// 每个字符占4位,因此需要生成64个随机数
size_t i;
for (i = 0; i < size; ++i) {
// 生成0~15之间的随机整数
int r = rand() % 16;
// 将随机整数转换成16进制字符
buf[i] = (r < 10) ? ('0' + r) : ('a' + r - 10);
}
}
int main() {
unsigned char buf[64];
generate_random_hex(buf, sizeof(buf));
printf("随机数: ");
size_t i;
for (i = 0; i < sizeof(buf); ++i) {
printf("%c", buf[i]);
}
printf("\n");
return 0;
}
```
该函数使用了C标准库中的rand()函数生成0~15之间的随机整数,然后将其转换成16进制字符。为了增加随机性,使用了当前时间作为随机数发生器的种子。最终生成的随机数保存在一个unsigned char数组中,每个字符占4位,因此需要生成64个随机数。最后,使用printf()函数输出生成的随机数。
用c写一个函数,生成256位、64位、42位、16位四个16进制随机数的函数
以下是一个生成四个指定位数的16进制随机数的C函数:
```c
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void generate_random_numbers(int num1_bits, int num2_bits, int num3_bits, int num4_bits) {
int num1_bytes = num1_bits / 8;
int num2_bytes = num2_bits / 8;
int num3_bytes = num3_bits / 8;
int num4_bytes = num4_bits / 8;
// Seed the random number generator with the current time
srand(time(NULL));
// Generate and print the first random number
printf("%0*X", num1_bytes * 2, rand() % (1 << (num1_bytes * 8)));
// Generate and print the second random number
printf("%0*X", num2_bytes * 2, rand() % (1 << (num2_bytes * 8)));
// Generate and print the third random number
printf("%0*X", num3_bytes * 2, rand() % (1 << (num3_bytes * 8)));
// Generate and print the fourth random number
printf("%0*X", num4_bytes * 2, rand() % (1 << (num4_bytes * 8)));
}
int main() {
generate_random_numbers(256, 64, 42, 16);
return 0;
}
```
这个函数将生成四个指定位数的16进制随机数,并将它们打印出来。要使用该函数,只需将所需的位数传递给函数即可。例如,要生成一个256位、64位、42位和16位的随机数,可以调用`generate_random_numbers(256, 64, 42, 16)`。
阅读全文