How to generate a code made of 4 hex digits?
the code meets the following conditions:
-first and third digits are the same
-second digit is even
-third digit is larger than 9
-fourth digit is random (has no conditions)
How to generate a code made of 4 hex digits? the code meets the
Share
There are a few things to note here. The first is that I generate 3 ‘codes’, since the third is always the same as the first.
To generate a random number from 0-15, use
random()%16I am using typeintto store these, it may not matter. When printing, I use%Xand not the more common%d, as%Xwill print it in hex. I print four hex digits (reusing code1 of course).The final part is to meet your conditions.
code1 is a random number in the range 0-5 and adds 10 to it (making it greater than 9)
code2 is
random()%8*2which generates a random number in the range 0-7 and then doubles it (making it even)code4 is just a random number from 0-15
You did not explain what to do with the generated code, so I just printed it. You could use the
sprintffunction if you need to print it into a string for further work.