Skip to content

Instantly share code, notes, and snippets.

@nuald nuald/int2str.cpp
Created Jul 18, 2017

Embed
What would you like to do?
Sample code to generate binary string from the integer
// 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
You can’t perform that action at this time.