简体   繁体   English

Base64 如何工作以及如何在其中进行编码/解码?

[英]How Does The Base64 Work and How To Encode/Decode in it?

I have a problem that asks me to encode a string to base64 format: I think I got it based on my code.我有一个问题要求我将字符串编码为 base64 格式:我想我是根据我的代码得到的。 The string: "Man" works and other short strings work.字符串:“Man”有效,其他短字符串有效。 But the string.但是字符串。 "this is a string:," doesn't work. “这是一个字符串:”不起作用。 And also I want to use the non-padding version, The questions asks me to use the non-padding version.而且我想使用非填充版本,问题要求我使用非填充版本。 Can you please explain the process of how to encode this string.你能解释一下如何编码这个字符串的过程吗? "this is a string.,"! “这是一个字符串。”! I have to turn the letters to ascii, and then turn them into binary and divide them into 6 bytes and then turn them to decimal and refer to a chart of ascii and then use them.我得把字母转成ascii,然后转成二进制,分成6个字节,再转成十进制,参考一张ascii的图表,然后用。 This is all I know!这就是我所知道的! But, please don't give me the code.但是,请不要给我代码。 I want to try out the coding on my own.我想自己尝试编码。 But please explain the process.但请说明过程。 There are no good videos explaining this topic!没有很好的视频来解释这个话题! And by the way, I am using python顺便说一句,我正在使用 python
Thank you谢谢

Here is the code I have:这是我的代码:

def decimal(binary):
    binary = str(binary); power = len(binary)-1
    values = []

    for x in binary:
        if x == "1":
            values.append((x, 2**power))
        power -= 1
    
    return sum([v for b,v in values if b == "1"])


string = "Man"

byte = ""
for x in string:
    byte += bin(ord(x))[0] + bin(ord(x))[2:]


values = []
for x in range(0, len(byte), 6):
    values.append(byte[x:x+6])

abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"

table = {x:abc[x] for x in range(len(abc))}
print("".join(table[decimal(x)] for x in values))

I am using python!我正在使用python!

Adjusted parts are explained using in-line comments:使用内嵌注释解释调整的部分:

import sys   # merely for manipulation with supplied arguments 
import math 

if len(sys.argv) == 1:
    string = "This is a string!!!"
else:
    string = ' '.join([sys.argv[i] for i in range(1,len(sys.argv))])

def decimal(binary):
    binary = str(binary); power = len(binary)-1
    values = []
    for x in binary:
        if x == "1":
            values.append((x, 2**power))
        power -= 1
    return sum([v for b,v in values if b == "1"])

byte = ""
for x in string.encode('utf-8'):     # ASCII is a proper subset of UTF-8
    byte += bin(x)[2:].rjust(8,'0')  # get binary string of length 8

byte = byte.ljust(math.ceil(len(byte)/6)*6,'0') # length must be divisible by 6 

values = []
for x in range(0, len(byte), 6):
    values.append(byte[x:x+6])

abc = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
table = {x:abc[x] for x in range(len(abc))}

print(string)                                 # input
padding = '=' * (((3 - len(string.encode('utf-8'))) % 3) % 3)
ooutput = "".join(table[decimal(x)] for x in values)
print(ooutput)
print(ooutput + padding)                       # for the sake of completeness

import base64   # merely for comparison/reference output
                # ↓↓↓ output from base64 module ↓↓↓
print(base64.b64encode(string.encode('utf-8')).decode('utf-8'))  

Output : .\SO\66724448.py ěščř ĚŠČŘ &.\SO\66724448.py Output : .\SO\66724448.py ěščř ĚŠČŘ &.\SO\66724448.py

ěščř ĚŠČŘ
xJvFocSNxZkgxJrFoMSMxZg
xJvFocSNxZkgxJrFoMSMxZg=
xJvFocSNxZkgxJrFoMSMxZg=
This is a string!!!
VGhpcyBpcyBhIHN0cmluZyEhIQ
VGhpcyBpcyBhIHN0cmluZyEhIQ==
VGhpcyBpcyBhIHN0cmluZyEhIQ==

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM