You are here:

C++/binary number storage


how can i generate random binary numbers and  store them in 1 byte form  

C++ uses the C library functions rand and srand and the macro RAND_MAX to support random number generation. In C you would include <stdlib.h> in C++ you should include <cstdlib>.

srand takes an unsigned int as its only parameter, and has a void return value.

rand takes no parameters and returns an int value.

You first use srand to seed the random number generator by passing it a positive integer seed value. If you wish to have as random sequence as possible, and not one repeated each time the program is executed, then the seed value needs to be different for each execution. Using a value derived from a time value is often used (time of day, time machine has been running).

After seeding the random number generator you call rand to obtain the next number in the pseudo random sequence. This is an integer value in the range 0 to RAND_MAX (which should be at least 32767). You wish to have a value in the range 0 to 255 (the largest 8-bit byte value) so your best bet is to convert the value returned by rand to a byte by effectively multiplying the result by 255 and dividing by RAND_MAX. However the nature of integers and the finite nature of the values represented by computers means that you need to take care doing this otherwise you will end up with a zero or less than ideal result.

255/RAND_MAX is going to be a fraction, which will be zero when expressed as an integer:

( rand() ) * ( 255/RAND_MAX ) will yield 0.

One obvious solution would be to multiply the random value by 255 first then divide the result by RAND_MAX:

( rand() * 255 ) / RAND_MAX

The above would yield the correct result, so long as

( rand() * 255 )

does not overflow.

For example, if rand returned a 32-bit signed integer and RAND_MAX were (2 to the 31) - 1, then multiplying RAND_MAX (the largest value returned from rand) by 255 would yield a result too big to express in a 32-bit integer. In reality the value would 'wrap' around to a smaller value.

The other obvious solution is to divide by RAND_MAX then multiply by 255:

( rand() / RAND_MAX ) * 255

However this always rounds down - so the only way to get 255 is for the random number generator to return RAND_MAX. One way around this would be to add an amount to the value returned from rand, so long as the result did not overflow. Another would be to divide 256 instead of 255 and test for the one case when 256 would be the result (i.e. when rand returns RAND_MAX) and explicitly set this to 255:

       int rndInt( rand() );
       unsigned char randByte(0);
       if ( RAND_MAX == rndInt )
         rndByte = 255;
         rndByte = ( rndInt / RAND_MAX ) * 256;

You can of course (and probably should) wrap the above in a function to make repeated use easier and tidier.

Another option is to use floating point variables for intermediate results so that the fractional parts are not lost:

       double rndDbl( rand() );
       unsigned char rndByte(((rndDbl*255)/RAND_MAX)+0.5);

But the performance of the conversion to and from floating point may be an issue.

You can replace the hardcoded value of 255 with the macro UCHAR_MAX from the C header file <limits.h>, or <climits> for C++. Or you can use the max() function of the std::numeric_limits C++ class template in the C++ <limits> header file:

       std::numberic_limits<unsigned char>::max()

256 could be replaced by a named constant that is one more than the maximum unsigned char value.

Note that the above assumes that the bit length of char (and unsigned char) is 8 - this is defined by the <climits> macro CHAR_BIT or the std::numberic_limits<unsigned char>::digits() function and is _at_ _least_ 8. You might therefore wish to define your own names for the byte extent values.

Note that I checked the above with the current C++ and C standards publications. The C standard is in fact for C 99 and not C 89 (or C 90; I am never sure which is the correct year to use) that the C++ standard (published in 1998) refers to.

Note also that I did not test any of the code snippets so I apologise if any of them contain mistakes.  


All Answers

Answers by Expert:

Ask Experts


Ralph McArdell


I am a software developer with more than 15 years C++ experience and over 25 years experience developing a wide variety of applications for Windows NT/2000/XP, UNIX, Linux and other platforms. I can help with basic to advanced C++, C (although I do not write just-C much if at all these days so maybe ask in the C section about purely C matters), software development and many platform specific and system development problems.


My career started in the mid 1980s working as a batch process operator for the now defunct Inner London Education Authority, working on Prime mini computers. I then moved into the role of Programmer / Analyst, also on the Primes, then into technical support and finally into the micro computing section, using a variety of 16 and 8 bit machines. Following the demise of the ILEA I worked for a small company, now gone, called Hodos. I worked on a part task train simulator using C and the Intel DVI (Digital Video Interactive) - the hardware based predecessor to Indeo. Other projects included a CGI based train simulator (different goals to the first), and various other projects in C and Visual Basic (er, version 1 that is). When Hodos went into receivership I went freelance and finally managed to start working in C++. I initially had contracts working on train simulators (surprise) and multimedia - I worked on many of the Dorling Kindersley CD-ROM titles and wrote the screensaver games for the Wallace and Gromit Cracking Animator CD. My more recent contracts have been more traditionally IT based, working predominately in C++ on MS Windows NT, 2000. XP, Linux and UN*X. These projects have had wide ranging additional skill sets including system analysis and design, databases and SQL in various guises, C#, client server and remoting, cross porting applications between platforms and various client development processes. I have an interest in the development of the C++ core language and libraries and try to keep up with at least some of the papers on the ISO C++ Standard Committee site at


©2016 All rights reserved.