Created
July 18, 2017 08:32
-
-
Save nuald/24bbdaf6dc9d90fc3906c353a78daa68 to your computer and use it in GitHub Desktop.
Sample code to generate binary string from the integer
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Sample code to generate binary string from the integer | |
// To compile, please use: | |
// $ clang++ int2str.cpp --std=c++11 -Weverything -Wno-c++98-compat | |
#include <cmath> | |
#include <cstdio> | |
#include <cstdlib> | |
#include <cstring> | |
#include <ctime> | |
constexpr long ROUNDS(10000000); | |
constexpr int UPPER_BOUND(1000000); | |
typedef char* char_ptr; | |
char_ptr int2str(int num); | |
int newRandom(); | |
char_ptr int2str(int num) { | |
auto digits = static_cast<size_t>(num > 0 ? log2(num) + 1 : 0); | |
auto sz = digits + 1; | |
auto result = static_cast<char_ptr>(malloc(sz)); | |
if (result) { | |
result[digits] = '\0'; | |
for (size_t i = 1; i <= digits; ++i) { | |
result[digits - i] = num % 2 ? '1' : '0'; | |
num >>= 1; | |
} | |
return result; | |
} | |
return nullptr; | |
} | |
int newRandom() { | |
// RANDMAX is not enough for high upper bounds | |
auto num = 0; | |
auto sz = static_cast<size_t>(log10(UPPER_BOUND)); | |
for (size_t j = 0; j < sz; ++j) { | |
auto newNum = num * 10 + rand() % 10; | |
if (newNum > UPPER_BOUND) { | |
break; | |
} | |
num = newNum; | |
} | |
return num; | |
} | |
int main(int, char **) { | |
srand(static_cast<unsigned>(time(nullptr))); | |
auto digits = 0L; | |
auto start = clock(); | |
for (int i = 0; i < ROUNDS; ++i) { | |
auto num = newRandom(); | |
auto result = int2str(num); | |
if (result) { | |
// Avoiding optimizations | |
digits += strlen(result); | |
free(result); | |
} | |
} | |
auto end = clock(); | |
auto diff = static_cast<double>(end - start) / CLOCKS_PER_SEC; | |
printf("Got %ld digits in %g second.\n", digits, diff); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment