Do you have any simple ways to make a value in a register in MIPS as an absolute value?
相关问题
- Null-terminated string, opening file for reading
- What's the difference between 0 and dword 0?
- Translate the following machine language code (0x2
- Where can the code be more efficient for checking
- How can I include a ASM program into my Turbo Basi
相关文章
- Why are memory addresses incremented by 4 in MIPS?
- How to generate assembly code with gcc that can be
- Select unique/deduplication in SSE/AVX
- Optimising this C (AVR) code
- Why does the latency of the sqrtsd instruction cha
- Difference in ABI between x86_64 Linux functions a
- x86 instruction encoding tables
- Why doesn't there exists a subi opcode for MIP
Simplest way of all. There is a pseudo instruction that does this:
will take the absolute value of the value in register $t1 and place it in $t1
Here's a size-optimized version of it. It's slower than the sra/xor/subu answer, due to branch prediction issues, but it's one instruction smaller:
This works because of the MIPS delay slot: if
$t0
is positive, thesubu
instruction to negate$t0
executes twice. You may need to enable.set noreorder
in your assembler.The easiest way would just to do a bit of binary math on the values.
http://en.wikipedia.org/wiki/Signed_number_representations describes how various systems store their negative numbers. I believe MIPS uses a two's complement scheme to store signed numbers. This makes it a bit harder than a bit flag, which could just be turned off by ANDing the number with 0b01111111, but it is still doable.
Here's a branch-less variant:
How does this work?
First,
$t1
is filled with the sign-bit of$t0
. So if$t0
is positive$t1
will be set to 0, and if$t0
is negative$t1
will be set to 0xFFFFFFFF.Next, each bit of
$t0
is inverted if$t1
is 0xFFFFFFFF, or left unchanged if$t1
is 0. It just so happens that inverting all bits of a number is the same as setting it to(-number)-1
(in two's complement).Finally, either 0xFFFFFFFF (which equals -1) or 0 is subtracted from the intermediate result.
So if
$t0
originally was negative you'll get:$t0 = ($t0 ^ 0xFFFFFFFF) - 0xFFFFFFFF
==(-$t0 - 1) - -1
==(-$t0 - 1) + 1
==-$t0
.And if it originally was positive you'll get:
$t0 = ($t0 ^ 0) - 0
==$t0
.Here is a pretty simple way to do it.