所以我将这个代码用于我的模拟器,将字节转换为十六进制
byteToHex(opcode) {
var tempCode = (opcode).toString(16).toUpperCase()
var addln = 4 - tempCode.length
var pad =""
for(var i = 0; i< addln; i++) {
pad = pad + "0"
}
var newCode = "0x"+ pad + tempCode
return newCode;
}
我有这个代码执行按位操作来获取操作码然后转换它以供使用。
this.opcode = (this.memory[this.pc] << 8) | this.memory[this.pc + 1]
console.log(this.memory)
console.log("before conversion", this.opcode)
this.opcode = this.byteToHex(this.opcode)
console.log(this.opcode)
//this just returns the first 'letter' of the opcode
switch (this.opcode & 0xF000)...
这是控制台输出
Array [ 240, 144, 144, 144, 240, 32, 96, 32, 32, 112, 70 more… ]
before conversion 0
0x0000
这意味着我错误地获取了操作码,但我不知道如何修复它。 为了更好地了解项目:Github
答案 0 :(得分:1)
这是一些按预期运行的代码。调试你的(不完整的)代码有点困难。由于StackOverflow是关于具体的问题和答案,我甚至不打算玩你需要解决的猜测/侦探游戏...
240d = 0xF0
144d = 0x90
[240,144]被视为单个16位大端数字是0xF090(英特尔的东西是小端,即最不重要的字节首先出现)
window.addEventListener('load', onDocLoaded, false);
var memoryContents = [240, 144, 144, 144, 240, 32, 96, 32, 32, 112];
function getTwoLocationsBigEndian(indexOfFirst)
{
var result = (memoryContents[indexOfFirst] << 8) | (memoryContents[indexOfFirst+1]);
return result;
}
function getTwoLocationsLittleEndian(indexOfFirst)
{
var result = (memoryContents[indexOfFirst+1] << 8) | (memoryContents[indexOfFirst]);
return result;
}
function byteToHex(opcode)
{
var tempCode = (opcode).toString(16).toUpperCase()
var addln = 4 - tempCode.length
var pad =""
for(var i = 0; i< addln; i++)
{
pad = pad + "0"
}
var newCode = "0x"+ pad + tempCode
return newCode;
}
function onDocLoaded(evt)
{
console.log("Memory contents: " + memoryContents);
var opcode = getTwoLocationsBigEndian(0);
console.log("***** BIG endian *****");
console.log("First 2 locs as a 16bit num (dec): " + opcode );
console.log("First 2 locs as a 16bit num (hex): " + byteToHex(opcode) );
opcode = getTwoLocationsLittleEndian(0);
console.log("***** LITTLE endian *****");
console.log("First 2 locs as a 16bit num (dec): " + opcode );
console.log("First 2 locs as a 16bit num (hex): " + byteToHex(opcode) );
}