How to generate an array of 8 bytes , each of these is random number in C
as in the t开发者_运维技巧itle, and each element of the array iv
should contain a random number between 0 and 255 . I have tried like:
char iv[8];
char buf[2];
int i, k;
srand(time(NULL));
for (i = 0; i <8; i++){
k = rand()%256;
iv[i] = (char)k;
}
Thanks in advance.
You should use unsigned char
for the array, not char
. The former is guaranteed to be able to hold the values from 0 to (at least) 255, but the latter may not be able to hold numbers greater than 127.
There's nothing wrong with your code. It's a bit excessive and "talkative" when it comes to generating and storing the number, and has magic constants where none are needed, but it should produce the wanted result.
The loop could be shortened to:
for (i = 0; i < sizeof iv; i++)
iv[i] = (char) rand();
Of course the randomness will be limited by whatever implementation of a PRNG your compiler and/or library is using.
You can directly assign the return value of rand() mod 256 to the array elements:
char iv[8];
int i;
srand(time(NULL));
for (i = 0; i <8; i++)
iv[i] = rand()%256;
This way can see some -ve numbers in the iv
array when you try to print it as an integer.
Lets say rand()%256
gave 255, which is 1111 1111
. Clearly the most significant bit of this is set, so when you try to print it as an integer it will be interpreted as a -ve number.
To avoid getting -ve numbers you'll have to declare the iv as an array of unsigned char:
unsigned char iv[8];
looks like ur solution could be something like this,
char myrand[8];
int *my1,*my2;
my1 = (int*)(myrand);
my2 = (int*)(myrand+4);
srand(time(NULL));
my1 = rand() % 0xffffffff;
my2 = rand() % 0xffffffff;
works faster you see. BTW I assume that int here is 4 bytes :-)
If you are using it as an Initiazation vector ( I guessed it seeing the variable named iv
) then it probably has to be unsigned as most cryptographic libraries expect a byte-array of eight unsigned values.
U should print using %u not %d. %u is the printf unsigned symbol, so it want take the sign bit into account, and print all the numbers as positive numbers.
Is this for use in a cryptographic algorithm? If so, you maybe shouldn't use rand(), it's not good enough for most cryptographic purposes.
精彩评论