简体   繁体   English

在node.js中的base64解码/编码中指定“替代字符”

[英]Specify 'alternate characters' in base64 decoding/encoding in node.js

I am trying to port some code from python to node. 我正在尝试将一些代码从python移植到节点。 The code is as follows: 代码如下:

//returns the UID contained in the var uid decoded to an int:
uid = 'ABCDE'
struct.unpack(">I", base64.b64decode(uid + 'A==', "[]"))[0] / 4

//encodes the UID int in uidint into the B64 UID:
uidint = 270532
base64.b64encode(struct.pack(">I", uidint * 4), "[]")[0:5]

I have already found a library that replaces the pack/unpacking functionality provided by python's struct class. 我已经找到一个库来替换python的struct类提供的打包/解包功能。

However, python's implementation of base64 has support for allowing alternate characters. 但是,python的base64 实现支持允许替换字符。 Unfortunately, node's does not. 不幸的是,节点没有。

Here is my work-in-progress port: 这是我在进行中的端口:

uid = 'ABCDE';
decoded = new Buffer(uid+'A==', 'base64').toString('ascii');
console.log(decoded);
test = jspack.Unpack(">I",decoded)[0] / 4;
console.log(test);

Currently the first console.log returns weird characters. 当前,第一个console.log返回奇怪的字符。 the second returns NaN. 第二个返回NaN。 Which makes sense why it'd do that. 为什么这样做会很有意义。

I was wondering if anyone knew how to replicate python's implementation of this pattern. 我想知道是否有人知道如何复制此模式的python实现。 I've been scanning through libraries on npm and didn't find anything that might suggest this as a feature. 我一直在npm上浏览库,没有发现任何可能暗示此功能的东西。

Just replace them manually before creating buffer: 只需在创建缓冲区之前手动替换它们:

new Buffer(
  (uid+'A==')
    .replace(/\+/g, '[')
    .replace(/\//g, ']')
, 'base64').toString('ascii')

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

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