File: base.hpp

package info (click to toggle)
ares 126-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 32,600 kB
  • sloc: cpp: 356,508; ansic: 20,394; makefile: 16; sh: 2
file content (38 lines) | stat: -rw-r--r-- 1,229 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
#pragma once

//required bytes: ceil(bits / log2(base))
//base57 => 128=22, 256=44, 512=88
//base62 => 128=22, 256=43, 512=86
//base64 => 128=22, 256=43, 512=86

#include <nall/arithmetic.hpp>

namespace nall::Encode {

template<u32 Bits, typename T> inline auto Base(T value) -> string {
  static const string format =
    Bits ==  2 ? "01"
  : Bits ==  8 ? "01234567"
  : Bits == 10 ? "0123456789"
  : Bits == 16 ? "0123456789abcdef"
  : Bits == 32 ? "0123456789abcdefghijklmnopqrstuv"
  : Bits == 34 ? "023456789abcdefghijkmnopqrstuvwxyz"  //1l
  : Bits == 36 ? "0123456789abcdefghijklmnopqrstuvwxyz"
  : Bits == 57 ? "23456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"  //01IOl
  : Bits == 62 ? "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
  : Bits == 64 ? "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz{}"
  : Bits == 85 ? "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz!#$%()+,-.:;=@[]^_`{|}~"  //\ "&'*/<>?
  : "";
  static const u32 size = ceil(sizeof(T) * 8 / log2(Bits));

  string result;
  result.resize(size);
  char* data = result.get() + size;
  for(auto byte : result) {
    *--data = format[value % Bits];
    value /= Bits;
  }
  return result;
}

}