Malak Sadek - 1 year ago 143

C++ Question

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

`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

Can anyone please help me? Thank you!

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

you mix binary, with integers

the encoding for `add s,t,d`

in BINARY is

"0000 00ss ssst tttt dddd d000 0010 0000"

so you'd have to concat "000000" + binary(2) + binary(3) + binary(1) + "00000100000"

where binary(x) is the binary represenation with fix 5 digits

in your case

000000 + 00010 + 00011 + 00001 + 00000100000

= 00000000010000110000100000100000, which converts to

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"

consists of 4 parts. 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

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**