Getting a byte of randomness [duplicate] - c++

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is the most random function in C++?
In C++, is this safe:
int main() {
srand(time(0));
unsigned char arr[10];
for(int i=0; i <sizeof(arr); ++i)
arr[i] = (unsigned char)rand();
}
Is there a better way to randomly fill a byte array in a platform independent way? failing that, is there a better way to do this on windows? (I know rand() isn't a very good PRNG, I'm just using it as an example).
Thank you!

What about using boost.random? The generators it uses can be passed to std::generate to fill your array, it's platform independent and headers-only. I would give a code sample but have no boost install available at the moment.
Edit: as mentioned: in C++0x (the upcoming standard), you can use tr1::random, which is essentially just the boost library becoming part of the standard C++ library.

Related

What is an efficient way to place random numbers in a buffer for writing to files? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 3 years ago.
Improve this question
I am trying to mess with using basic Linux system calls and writing good code by writing a program that will write random bytes to a file. I've envisioned a couple different ways of doing this, but I'm curious of what methods are more efficient. Please feel free to give me improvements on my code or suggest completely different methods; I'm just trying to improve.
Currently, I'm generating random uint32_t's using mt19937 from C++11's random and placing them in a buffer using memcpy before writing to the file. Is this a very efficient way to do this?
Would I be better off initializing the buffer to 0 with a memset and using or'ing/bit-shifting? With that, I am forgetting how to/if there is a way to do something like *(buffer + offset) |= (random32 << BUF_SIZE - sizeof(random32) * currIndex) and get C++ to place all 32 bits rather than a single char.
//Here's the actual buffer manipulation/write code I currently have
std::mt19937 rand(std::chrono::system_clock::now().time_since_epoch().count());
for(ssize_t i = 0; i < size; i += BUF_SIZE)
{
//Fill the buffer with random uint32_t's (the buffer is a multiple of 32 right now)
char buffer[BUF_SIZE];
for(int j = 0; j < BUF_SIZE; j += sizeof(uint32_t))
{
uint32_t num = rand();
std::fprintf(stderr, "DEBUG: generated random number %x\n", num);
std::memcpy(buffer + j, &num, sizeof(num));
}
// Write buffer to file
ssize_t bytes_left = size - i;
ssize_t bytes_to_write = BUF_SIZE > bytes_left ? bytes_left : BUF_SIZE;
std::fprintf(stderr, "DEBUG: writing %zu bytes to buffer\n", bytes_to_write);
if(write(fd, buffer, bytes_to_write) != bytes_to_write)
{
std::fprintf(stderr, "Failed to write at %zu", i);
exit(EXIT_FAILURE);
}
}
Do this:
::std::array<char, BUF_SIZE> buffer;
::std::generate(buffer.begin(), buffer.end(), rand);
instead of the loop you're currently using to fill up the buffer. Then adjust the rest of the program to use a buffer that's an array that has it's own size method and the like rather than a bare char array like you have now.
That's more the C++ way than what you're doing. Minimize the use of bare pointers and arrays. Use the standard algorithms where possible. If you find yourself writing a for loop, look to see if the algorithms library has already written the loop for you.
And that goes for code that isn't already in the standard library as well. If you find yourself writing a for loop, stop. Instead, figure out how to abstract what that for loop is doing into a reusable function so that you can write the for loop once and use it in a lot of situations.
And if you want to understand how the standard library works, then take it upon yourself to write those functions.
Don't Repeat Yourself is one of the absolutely most important programming principles. Larry Wall famously recast it as 'laziness'. Learn how to never repeat yourself. If the standard library makes you uncomfortable because you don't know what it's doing, try using compiler explorer to see the assembly language. And try writing the standard library functions yourself. Knowing your tools up, down, and sideways is also really important. So this work is worth doing.
But, that's what you should be doing, not repeating yourself and training yourself to do it over and over again. Train yourself to do it the right way. And if you're uncomfortable with not knowing the details, write the details instead of writing it the wrong way so you can see the details.

Is this a reliable way of generating a GUID? [duplicate]

This question already has answers here:
Platform-independent GUID generation in C++?
(6 answers)
Closed 6 years ago.
I'm trying to generate a GUID in a platform agnostic manner, most search results suggest using BOOST or platform specific libraries. I remember once coming across the following snippet and I was wondering if this is a reliable way of generating GUID's:
unsigned int generateGuid()
{
char c;
return (unsigned int)&c;
}
More specifically, does this guarantee a unique value always? And if not, what are some good lightweight and cross-platform approaches of doing this?
A basic example:
#include <boost/uuid/uuid.hpp> // uuid class
#include <boost/uuid/uuid_generators.hpp> // generators
#include <boost/uuid/uuid_io.hpp> // streaming operators etc.
int main() {
boost::uuids::uuid uuid = boost::uuids::random_generator()();
std::cout << uuid << std::endl;
}
Example output:
No it is not. This function will return some address from stack depending on where it is called. In two subsequent calls or tight loop it will be always the same address. For example in Visual Studio the default stack size is 1 MB, I think, so in the best case you will get one million unique values. Typical program does not use more than 1KB of stack so in that case you will get at most one thousand unique values.

Declare a Big Integer in C++ [duplicate]

This question already has answers here:
STL BigInt class implementation
(3 answers)
Closed 7 years ago.
I am trying to run this algorithm in c++ in order to get a big number
#include<iostream>
using namespace std;
int main()
{
int num,factorial=1;
cout<<" Enter Number To Find Its Factorial: ";
cin>>num;
for(int a=1;a<=num;a++)
{
factorial=factorial*a;
}
cout<<"Factorial of Given Number is ="<<factorial<<endl;
return 0;
}
How can I declare a Big Integer like in Java instead of an int?
There is no big-integer support in the C++ standard library. A common choice for big-number arithmetic is GMP. After downloading and installing the library, in your code you would #include <gmpxx.h> and declare mpz_class factorial instead of int factorial, then link against GMP.
Linking with GMP can be done in an IDE, by adding GMP in your editor’s compile settings; or by adding -lgmp to your compilation command (e.g., g++ or clang++).
There is no arbitrary-precision arithmetic in c++ standard library. You'll need to implement it yourself using an array of integers, or use an existing non-standard library.
Try unsigned long long int for just convenience.
I just want to leave it as comment but I have low repu for commenting..
There is no standard support for arbitrary-precision integers. However, a few libraries are available for handling big integers:
GNU MP Bignum Library
InfInt
C++ BigInt class
BigDigits multiple-precision arithmetic (in C)
BigIntegerCPP (only supports addition and multiplication)
C++ Big Integer Library (no longer maintained)

How to store a very large number in c++ [duplicate]

This question already has answers here:
How to store extremely large numbers?
(4 answers)
Closed 5 years ago.
Is there any way to store a 1000 digit number in c++? I tried storing it to an unsigned long double but it is still to large for its type.
You may find your answer here How to store extremely large numbers? GMP answer sounds right, ie this is what it does with pi digits https://gmplib.org/pi-with-gmp.html
You have to implement it yourself or use a library for it. In particular I love GMP: https://gmplib.org/ , which is an C implementation of Big Int/Float and has C++ wrapper
Use a custom class for your number, something like this:
#include <vector>
#include <iostream>
class large_num {
private:
int digits; // The number of digits in the large number
std::vector<int> num; // The array with digits of the number.
public:
// Implement the constructor, destructor, helper functions etc.
}
For a very large number just add each digit to the vector. For example if the number if 123456, then you do num.pushback(); In this case push all the digits 1,2, .. 6. You can store a extremely large numbers this way.
You should try this one
http://sourceforge.net/projects/libbigint/
great library for things like this.
also you can use boost.
http://www.boost.org/doc/libs/1_53_0/libs/multiprecision/doc/html/boost_multiprecision/intro.html
also one of the most commons is
https://gmplib.org/
Depends on the usage.If you need to do computation on it, probably go with the Big Int Library. If not and only aim is storing, store it in an array with each digit stored in one array element.

Init local array with zeros in C++ [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
C and C++ : Partial initialization of automatic structure
I'm looking for a fast way to init local array with zeros. (By "Fast", I mean "Fast to type.") When I do the following:
HANDLE hHandles[32] = {0};
does it zero out the first element or all 32?
It initializes all the 32 elements to zero.
See this surprisingly popular answer for details/alternatives. The difference between C and C++ seems to be that in C++ {} will do zero-initialization as well.