int main(){
uint8_t *wdata = NULL;
wdata = calloc(5, sizeof(uint8_t));
for (int j =0;j<5;j++){
wdata[j] = rand();
}
}
The rand()
function generates 16 bits of data. How do I generate 8 bits of random values? Do I need to use a custom function for the same?
How to generate an 8 bit random number in C
Given code such as
uint8_t *wdata = calloc( 5, sizeof( uint8_t ) );
something like
for ( int j = 0;j < 5; j++ )
{
wdata[ j ] = rand();
}
will work fine.
Integer assignment to an unsigned value truncates, which is exactly what you want. See 6.5.16.1 Simple assignment of the C Standard .
Note that RAND_MAX
is guaranteed by 7.22.2 Pseudo-random sequence generation functions , paragraph 5 to be at least 32767, which is "wider" than 8 bits, so the result is guaranteed to "fill up" an 8-bit variable.
Because 8 bit number can contain maximum 0
- 255
. so if i divide rand()%256
we get 8 bit random number.
int main(){
uint8_t *wdata = NULL;
wdata = calloc(5, sizeof(uint8_t));
for (int j =0;j<5;j++){
wdata[j] = rand()%256;
}
}
for more randomness you use some prime number add or subtract difference after dividing from 256
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.