Dieter Menne
Dieter Menne

Reputation: 10215

Hash to string with given character set

The usual hash-functions, e.g. from digest create hex output. I want to create a hash with character from a given set, e.g [a-z,0-9]; no strong cryptographic security is required.

Using base64encode on a hashed string comes close, but the character set is fixed in that function.

Upvotes: 0

Views: 146

Answers (1)

Dieter Menne
Dieter Menne

Reputation: 10215

It is ugly div/mod manipulation for an arbitrary character table, so I decided to use a 32 character table without l 0, O

#include <Rcpp.h>
using namespace Rcpp;

static const std::string base32_chars = "abcdefghijkmnpqrstuvwxyz23456789";

// [[Rcpp::export]]
String encode32(uint32_t hash_int, int length = 7)
{
  String res;
  std::ostringstream oss;
  if (length > 7 || length < 1) 
    length = 7;
  for (int i = 0; i < length; i++) {
    oss << base32_chars[hash_int & 31];
    hash_int = hash_int >> 5;
  }
  res = oss.str();
  return res;
}

/*** R
print(encode32(digest::digest2int("Hellod")))
*/

Upvotes: 1

Related Questions