我正在尝试将字节数组转换为javascript中的字符串。但首先,我必须将一个对象强制转换为字节数组。
以下是一个示例:
function Main(obj)
{
//Obj is an object (in fact, it's a bytes array
var str = FromBytesToString(obj);
//str must be a string, computed from the obj
return str;
}
任何人都知道如何做到这一点?
提前致谢,
纪尧姆
编辑:一些准确性:
1)我使用这段代码在Windows应用程序(C#)中调用javascript:
private string ExecuteScript(byte[] buffer)
{
//Load script (using StreamReader)
string script = LoadScript(@"C:\script.js");
//Parse script
ScriptEngine engine = new ScriptEngine("Jscript");
ParsedScript parsedScript = engine.Parse(script);
//Run script, calling "Main" method
return parsedScript.CallMethod("Main", buffer);
}
此代码使用ScriptEngine代码,找到here。它使用Windows脚本引擎
2)Javascript代码
以下是javascript代码:
function Main(bytearray)
{
//Transform the bytearray in string
str = StringFromBytes();
//Do some stuff (replace/etc)
//sent back the new string
return str;
}
问题是因为参数“bytearray”是一个C#字节数组,而javascript只知道它作为对象。如果我使用以下方法:
function StringFromByte(array)
{
var b = array;
var s = "";
for (var i = 0; i < b.length; i++)
s += String.fromCharCode(b[i]);
return s;
}
“s + = String.fromCharCode(b [i])”行中显示的错误; - &gt;预计会有一个数字......
答案 0 :(得分:0)
你可以;
var b = [0x61, 0x62, 0x63];
var s = "";
for (var i = 0; i < b.length; i++)
s += String.fromCharCode(b[i]);
s === "abc"
答案 1 :(得分:0)
如何在Main函数中正确调用String From Byte,将bytearray传递给它?
function Main(bytearray)
{
//Transform the bytearray in string
str = StringFromBytes(bytearray); //<<<< this was missing
//Do some stuff (replace/etc)
//sent back the new string
return str;
}