Last active
August 7, 2016 21:05
-
-
Save rockarts/0c2539a8c64dc81e1c903133ab4b3e05 to your computer and use it in GitHub Desktop.
Base58 Encode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| using System; | |
| using Microsoft.VisualStudio.TestTools.UnitTesting; | |
| namespace UnitTestProject1 | |
| { | |
| [TestClass] | |
| public class UnitTest1 | |
| { | |
| [TestMethod] | |
| public void ShouldEncodeIntegerToBase58() | |
| { | |
| int numberToEncode = 299542347; | |
| Assert.AreEqual("steve", Encode(numberToEncode)); | |
| } | |
| [TestMethod] | |
| public void ShouldDecodeBase58ToInteger() | |
| { | |
| string stringToDecode = "steve"; | |
| Assert.AreEqual(299542347, Decode(stringToDecode)); | |
| } | |
| //Ported from https://www.flickr.com/groups/api/discuss/72157616713786392/ | |
| public string Encode(int num) | |
| { | |
| string alphabet = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; | |
| int baseCount = alphabet.Length; | |
| string encoded = ""; | |
| while (num > 0) | |
| { | |
| int remainder = num % baseCount; | |
| num = Convert.ToInt32(num / baseCount); | |
| encoded = alphabet[remainder].ToString() + encoded; | |
| } | |
| return encoded; | |
| } | |
| private int Decode(string stringToDecode) | |
| { | |
| string alphabet = "123456789abcdefghijkmnopqrstuvwxyzABCDEFGHJKLMNPQRSTUVWXYZ"; | |
| int decoded = 0; | |
| int multi = 1; | |
| while (stringToDecode.Length > 0) | |
| { | |
| string digit = stringToDecode.Substring(stringToDecode.Length - 1); | |
| decoded = decoded + (multi * alphabet.IndexOf(digit)); | |
| multi = multi * alphabet.Length; | |
| stringToDecode = stringToDecode.Substring(0, stringToDecode.Length - 1); | |
| } | |
| return decoded; | |
| } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment