Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we create a random uint8_ number using a simple casting?

Tags:

c

In my compute, the function rand(); in C language outputs a 32-bit number.

Is the following code will generate a random uint_8 number? Or it can be platform-dependent?

uint8_t var=(uint8_t) rand();

I don't want to use modulo operation, due to time complexity of calculating modulo.

like image 449
user3563894 Avatar asked Nov 02 '21 13:11

user3563894


2 Answers

This code will indeed convert the return value of rand to a value of type uint8_t. The conversion happens by essentially truncating all but the lowest order 8 bits.

As far as using the modulo operator, most compilers are smart enough to convert modulo by 2n to a bitwise AND with a value with the n lower order bits set.

Note that for simple uses this is fine, however if you want to generate random numbers suitable for cryptographic purposes, or if you want to ensure better random distribution, you should use a crypto library such as OpenSSL instead of the rand function.

like image 147
dbush Avatar answered Oct 03 '22 13:10

dbush


I don't want to use modulo operation, due to time complexity of calculating modulo.

Modern compilers are smart enough to do not use division when it is not absolutely necessary.

All below result in the identical generated code:

uint8_t foo(void)
{
    return rand();
}

uint8_t foo1(void)
{
    return (uint8_t)rand();
}

uint8_t foo2(void)
{
    return rand() % 0x100;
}

uint8_t foo3(void)
{
    return rand() & 0xff;
}

And the generated code:

foo():
        sub     rsp, 8
        call    rand
        add     rsp, 8
        ret
foo1():
        sub     rsp, 8
        call    rand
        add     rsp, 8
        ret
foo2():
        sub     rsp, 8
        call    rand
        add     rsp, 8
        ret
foo3():
        sub     rsp, 8
        call    rand
        add     rsp, 8
        ret
like image 42
0___________ Avatar answered Oct 03 '22 13:10

0___________