Skip to content

Instantly share code, notes, and snippets.

@Enichan
Created December 18, 2022 12:38
Show Gist options
  • Save Enichan/977c16027ff6ab22f25893093768249f to your computer and use it in GitHub Desktop.
Save Enichan/977c16027ff6ab22f25893093768249f to your computer and use it in GitHub Desktop.
Double dabble algorithm in C#
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DoubleDabble {
class Program {
static void Main(string[] args) {
var value = 330382099;
var result = ToString(value);
Console.WriteLine(result);
Console.ReadKey();
}
static string ToString(int value) {
byte[] chars = DoubleDabble(value);
var s = new StringBuilder(int32CharCount + 1);
int i;
if (value < 0) {
s.Append('-');
}
for (i = chars.Length - 1; i >= 0; i--) {
if (chars[i] != '0') {
break;
}
}
for (; i >= 0; i--) {
s.Append((char)chars[i]);
}
return s.ToString();
}
static string ToString(uint value) {
byte[] chars = DoubleDabble(value);
var s = new StringBuilder(int32CharCount);
int i;
for (i = chars.Length - 1; i >= 0; i--) {
if (chars[i] != '0') {
break;
}
}
for (; i >= 0; i--) {
s.Append((char)chars[i]);
}
return s.ToString();
}
static byte[] DoubleDabble(int value) {
return DoubleDabble((uint)(value < 0 ? -value : value));
}
const int int32Bits = 32;
const int int32CharCount = 10;
static byte[] DoubleDabble(uint value) {
byte[] chars = new byte[int32CharCount];
for (int i = 0; i < int32Bits; i++) {
// carry and shift for initial bits
byte carry = (value & 0x80000000) == 0x80000000 ? (byte)1 : (byte)0;
value <<= 1;
for (int c = 0; c < int32CharCount; c++) {
// adjust
if (chars[c] >= 5) {
chars[c] += 3;
}
// shift
chars[c] <<= 1;
// carry
chars[c] += carry;
carry = (chars[c] & 0b10000) == 0b10000 ? (byte)1 : (byte)0;
// truncate
chars[c] &= 0b1111;
}
}
// turn 0-9 values into '0'-'9' ascii
for (int c = 0; c < int32CharCount; c++) {
chars[c] += 48;
}
return chars;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment