在 go 中编码可执行文件并在 javascript 中解码不起作用
时间:2024-04-07
浏览:390
作者:佚名
珍惜时间,勤奋学习!今天给大家带来《在 go 中编码可执行文件并在 javascript 中解码不起作用》,正文内容主要涉及到等等,如果你正在学习Golang,或者是对Golang有疑问,欢迎大家关注我!后面我会持续更新相关内容的,希望都能帮到正在学习的大家!
问题内容
我正在 go 中编码可执行文件,并尝试在 javascript 中对其进行解码。
解码 javascript 中编码的 string 不会产生匹配的文件。我能够对像 "这是一个测试字符串" 这样的字符串进行编码,并在 javascript 中对其进行解码,并且工作正常。但是,当我使用可执行应用程序并执行相同的操作时,解码后的文件比编码前的文件大。
我做错了什么?谢谢!
这是我正在使用的测试可执行文件。它是 c++ 语言,使用 g++ 编译并使用输出。
#include <iostream>
int main(void) {
char test1[] = "hello";
std::cout << "test1: " << test1 << std::endl;
char test2[] = "world";
std::cout << "test2: " << test2 << std::endl;
char test3[] = "foobar";
std::cout << "test3: " << test3 << std::endl;
return 0;
}
这是我用来将文件转换为 bytes 的 go 应用程序。
package main
import (
"fmt"
"github.com/atotto/clipboard"
"io/ioutil"
)
func main() {
bytes, err := ioutil.readfile("/path/to/file/a.out")
if err != nil {
fmt.println(err)
}
enc := make([]byte, base64.rawstdencoding.encodedlen(len(bytes)))
base64.rawstdencoding.encode(enc, bytes)
fmt.println("byte size: ", len(bytes))
fmt.println("encoded byte size: ", len(enc))
clipboard.writeall(string(enc))
}
这是我尝试在 javascript 中解码和保存文件的方法。
let decodedBytes = atob("put the bytes here from your clipboard from running the go app");
fs.writeFileSync(
"/destination/to/save/file",
decodedBytes
);解决方案
我明白了。经过一番研究和阅读后,我发现了 this question 和 this article。最初这个问题对我没有帮助,但读完那篇文章一段时间后,我尝试了一些示例,并能够让其中一个工作。我能够让 solution 1 工作。这是我现在要让它工作的 javascript。
保存的文件与源文件完全相同。
function b64ToUint6(nChr) {
return nChr > 64 && nChr < 91
? nChr - 65
: nChr > 96 && nChr < 123
? nChr - 71
: nChr > 47 && nChr < 58
? nChr + 4
: nChr === 43
? 62
: nChr === 47
? 63
: 0;
}
function base64DecToArr(sBase64, nBlockSize) {
var sB64Enc = sBase64.replace(/[^A-Za-z0-9\+\/]/g, ""),
nInLen = sB64Enc.length,
nOutLen = nBlockSize
? Math.ceil(((nInLen * 3 + 1) >>> 2) / nBlockSize) * nBlockSize
: (nInLen * 3 + 1) >>> 2,
aBytes = new Uint8Array(nOutLen);
for (
var nMod3, nMod4, nUint24 = 0, nOutIdx = 0, nInIdx = 0;
nInIdx < nInLen;
nInIdx++
) {
nMod4 = nInIdx & 3;
nUint24 |= b64ToUint6(sB64Enc.charCodeAt(nInIdx)) << (18 - 6 * nMod4);
if (nMod4 === 3 || nInLen - nInIdx === 1) {
for (nMod3 = 0; nMod3 < 3 && nOutIdx < nOutLen; nMod3++, nOutIdx++) {
aBytes[nOutIdx] = (nUint24 >>> ((16 >>> nMod3) & 24)) & 255;
}
nUint24 = 0;
}
}
return aBytes;
}
let decodedBytes = base64DecToArr("bytes to decode");
fs.writeFileSync(
"/destination/to/save/file",
decodedBytes
);今天关于《在 go 中编码可执行文件并在 javascript 中解码不起作用》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
本文内容来源于互联网,如有侵权请联系删除。
近期热门
11.18
11.15
站内热门
最新文章
热门专题
