javascript函数btoa的C#版本 [英] C# version of the javascript function btoa

查看:60
本文介绍了javascript函数btoa的C#版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将一些内容从js重新编码为c#,该代码在字符串unichar上利用js中的btoa方法将其转换为base64.但是,据我所知,javascrpt使用的编码与c#中可用的编码不同.我需要编码完全相同,并且在所有这些语言中都不能返回不同的值.我已经尝试设置一个nodejs服务器并对其进行获取请求,以便以这种方式运行编码,但是这太慢且太不稳定了.我的印象是我需要制作自己的编码表,但是我不知道从哪里开始或如何实现.如果有人可以提供帮助,将不胜感激.

I need to recode something from js to c# that utilises the btoa method in js on a string of unicode chars to convert them to base64. However, as far as I know the encoding used by javascrpt is different to all those available in c#. I need the encoding to be exactly the same and not return different values across these languages. I have tried setting up a nodejs server and making get requests to it, in order to run the encoding that way, but this is far too slow and unstable. I am under the impression I would need to make my own encoding table but I have no idea where to start or how to implement this. If anyone could help that would be greatly appreciated.

tl; dr:javascript的btoa返回的值与c#中的base 64编码不同.我需要将其设置为相同的值.

tl;dr: javascript's btoa returns different value than base 64 encoding in c# does. I need it to be the same values.

代码和输出:

c#:
String fromChar = new 
String(247,71,186,8,125,72,2,1.0078125,0.003936767578125);
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(fromChar);
Console.WriteLine(System.Convert.ToBase64String(plainTextBytes));

output = w7dHwroIfUgCAQA=


javascript:
var x = btoa(String.fromCharCode(247,71,186,8,125,72,2,1.0078125,0.003936767578125);
console.log(x)

output = 
90e6CH1IAgEA

我知道前面的示例使用utf8编码,而js不使用utf8编码,问题是.net中没有与javascript编码匹配的编码.

I am aware the former example uses utf8 encoding which js does not, the problem is there is no encoding in .net that matches the javascript encoding.

试图比较c#和javascript的字节数组,但是问题是btoa函数使用了未命名的编码,因此如果不假设它类似于以下内容,我实际上无法获取字节来为其打印字节数组utf8,不是.

Tried to compare the byte arrays of both c# and javascript but the problem is the btoa function uses an unnamed encoding, so I can't actually get the bytes to print the byte array for it without assuming it is something like utf8 which it is not.

推荐答案

解决了.对于任何想知道使用的编码是iso编码的人.可以使用以下c#方法来复制javascript中的btoa函数:

Worked it out. For anyone wondering the encoding used is iso encoding. The btoa function in javascript can be replicated by using the following c# method:

public string encoding(string toEncode)
{
byte[] bytes= Encoding.GetEncoding(28591).GetBytes(toEncode);
string toReturn = System.Convert.ToBase64String(bytes);
return toReturn;
}

这篇关于javascript函数btoa的C#版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆