Thursday, July 10, 2014

A recursive function for calculating binary representation of base10 integers in R

A recursive function for calculating binary representation of base10 integers in R

binstr = function(i) {
    if (i) {
        paste(binstr(i %/% 2), i %% 2, sep="")
    }
    else {
        ""
    }
}

The idea behind this algorithm can be explained by the figure below:

image/svg+xml

This can also be implemented in c++, although a bit more complicated (this one is not recursive):

#include <string>
#include <vector>
#include <stdlib.h>
#include <stdio.h>
#include "RcppArmadillo.h"

// via the depends attribute we tell Rcpp to create hooks for
// RcppArmadillo so that the build process will know what to do
//
// [[Rcpp::depends(RcppArmadillo)]]


using namespace Rcpp;
using namespace std;

// The vector_join function is from Juri TimoŇ°in
// http://dracoater.blogspot.nl/2010/03/joining-vector-and-splitting-string-in.html
template <class T>
string vector_join( const vector<T>& v, const string& token ){
  ostringstream result;
  for (typename vector<T>::const_iterator i = v.begin(); i != v.end(); i++){
    if (i != v.begin()) result << token;
    result << *i;
  }
  return result.str();
}

template <class T>
std::string binstr(T somebyte) {
 int int10 = (int) somebyte;
 if(int10 == 0) {
  return "0";
 }
 std::vector<int> binvec;
 while(int10 != 0) {
  binvec.push_back(int10 % 2);
  int10 = (int) int10 / 2;
 }
 std::reverse(binvec.begin(), binvec.end());
 return vector_join(binvec, "");
}

// [[Rcpp::export]]
std::string binstrFromInt(int x) {
 return binstr(x);
}

0 comments: