简体   繁体   English

C ++中的MIPS转换器,如何转换为十六进制

[英]MIPS translator in C++, how to convert to hex

I am creating a translator in C++ that accepts MIPS assembly instructions such as "add 1, 2, 3" as in add register 2 and 3 and place the result in register 1. Eventually, I save everything into a string representing the machine code that is supposed to be the output, however I want to display it in hexadecimal format, instead it outputs in decimal 我正在C ++中创建一个接受MIPS汇编指令的转换器,如添加寄存器2和3中的“ add 1,2,3”,然后将结果放入寄存器1中。最后,我将所有内容保存到一个表示机器代码的字符串中应该是输出,但是我想以十六进制格式显示,而是以十进制输出

    assembly = "000000" + m[3].str() + m[4].str() + m[2].str() + "00000" + funct;
    cout << assembly << endl;

The literal output is correct = 00000023100000100000 However I want it to output as = 00430820 文字输出正确= 00000023100000100000但是我希望它输出为00430820

Can anyone please help me? 谁能帮帮我吗? Thank you! 谢谢!

you mix binary, with integers 您将二进制与整数混合

the encoding for add s,t,d in BINARY is BINARY中add s,t,d的编码为

"0000 00ss ssst tttt dddd d000 0010 0000" “ 0000 00ss ssst tttt dddd d000 0010 0000”

so you'd have to concat "000000" + binary(2) + binary(3) + binary(1) + "00000100000" 因此,您必须连接“ 000000” +二进制(2)+二进制(3)+二进制(1)+“ 00000100000”

where binary(x) is the binary represenation with fix 5 digits 其中binary(x)是具有固定5位数字的二进制表示形式

in your case 在你的情况下

000000 + 00010 + 00011 + 00001 + 00000100000 000000 + 00010 + 00011 + 00001 + 00000100000

= 00000000010000110000100000100000, which converts to = 00000000010000110000100000100000,转换为

00430820h ("0000"=0, "0000"=0, "0100"=4, "0011" = 3, "0000"=0, "1000"=8, "0010"=2, "0000"=0) 00430820h(“ 0000” = 0,“ 0000” = 0,“ 0100” = 4,“ 0011” = 3,“ 0000” = 0,“ 1000” = 8,“ 0010” = 2,“ 0000” = 0)

if you take a closer look at the encoding, you see 如果仔细看一下编码,您会看到

"000000ssssstttttddddd00000100000" “ 000000ssssstttttddddd00000100000”

consists of 4 parts. 由4部分组成。 first is constant which defines the instruction, and 3 are defining the registers to be used 第一个是定义指令的常量,第三个是定义要使用的寄存器

   "00000000000000000000000000100000" = 0x00000020
+  "000000sssss000000000000000000000" (which is s left shifted by 21)
+  "00000000000ttttt0000000000000000" (which is t left shifted by 16)
+  "0000000000000000ddddd00000000000" (which is d left shifted by 11)

so the easiest way to encode this instruction is: 因此,对该指令进行编码的最简单方法是:

uint32_t i = 0x00000020 + (s<<21)  + (t<<16) + (d<<11);

print this in hex, and you get: 00430820 以十六进制打印,您将得到:00430820

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

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