Compress large Integers into smallest possible string

后端 未结 6 1604
夕颜
夕颜 2020-12-08 21:04

I have a bunch of 10 digit integers that I\'m passing in a URL. Something like: \"4294965286\", \"2292964213\". They will always be positive and always be 10 digits.

6条回答
  •  一向
    一向 (楼主)
    2020-12-08 21:44

    You could use base64 encoding to reduce the data into seven characters. You need five bytes to represent the number, and those can be encoded into eight characters using base64, but that last character is always the filler =, so it can be removed:

    long value = 4294965286;
    
    // get the value as an eight byte array (where the last three are zero)
    byte[] data = BitConverter.GetBytes(value);
    // encode the first five bytes
    string base64 = Convert.ToBase64String(data, 0, 5).Substring(0, 7);
    Console.WriteLine(base64);
    

    Output:

    Jvj//wA
    

    To decode the text, you add the = again, decode it, and read it as a number:

    // create an eight byte array
    byte[] data = new byte[8];
    // decode the text info five bytes and put in the array
    Convert.FromBase64String(base64 + "=").CopyTo(data, 0);
    // get the value from the array
    long value = BitConverter.ToInt64(data, 0);
    
    Console.WriteLine(value);
    

    Output:

    4294965286
    

    Two of the characters that base64 uses are not suitable for use in an URL, so you can replace them with other characters, and then replace them back. The + and / characters could for example be replaced by - and _.

提交回复
热议问题