我想基本上删除我的前导零。当我打印出例如17的数字是00000 0000 0000 0000 0000 0000 00001 0001但是要删除那些前导零。因为sparc机器是打印出来的,我需要使用某种循环或逻辑或移位功能来完成这项工作。
这是我打印二进制文件的伪代码
store input, %l1 ! store my decimal number in l1
move 1,%l2 !move 1 into l2 register
shift logical left l2,31,l2 !shift my mask 1 31 times to the left
loop:
and l2,l1,l3 ! do and logic between l1 and l2 and put this in l3
compare l3,0 compare l3 zero
bne print 1 !branch not equal to zero, to print 1
if equal to 0
print zero
print 1:
print a 1
go: increment counter
compare counter 32
if counter less than 32 return to loop
shift l2 to the right to continue comparison
所以这就是我要做的事情,我的输入是l1是17
00000 0000 0000 0000 0000 0000 00001 0001
10000 0000 0000 0000 0000 0000 00000 0000我的面具1左移31次
这个pseucode将我的输入十进制打印成二进制。但是我如何才能删除前导零呢?
因为在机器内部的sparc 17输入是
<00> 0000 0000 0000 0000 0000 0000 0001 00001答案 0 :(得分:0)
您可以创建标签,例如go
和print 1
(更常见的是全部大写,没有空格,仅供参考)。因此,从bne
开始,您应始终打印1
,或者查看是否需要打印0
:
! same initialization
mov 0, l4 ! Initialize a flag to avoid printing
LOOP:
and l2, l1, l3 ! do and logic between l1 and l2 and put this in l3
cmp l3, 0 ! Is this a 0 digit?
bne ALWAYS_PRINT ! If it's not 0, then it must be 1 (was "bne print 1")
cmp l4, 1 ! Should we be printing the 0?
be PRINT_VALUE ! Yes, we need to print the 0 because we have seen a 1
ba INCREMENT ! We should not be printing the 0, so check the next
! digit (ba is "branch always")
ALWAYS_PRINT: !
mov 1, %l4 ! Note that we want to always print for the
! rest of the loop
PRINT_VALUE: ! Do whatever you're doing to print values
print value in l3 ! Always print the value
INCREMENT: ! Formerly your "go:" label
! same logic
! AFTER LOOP IS DONE LOGIC
cmp l4, 0 ! If the flag was never set, then the value is 0
! Alternatively, you could just compare the value to 0
! and skip the loop entirely, only printing 0 (faster)
bne DO_NOT_PRINT ! If it was set (1), then do nothing
print zero ! If it wasn't set, then print the 0
DO_NOT_PRINT:
要稍微浏览一下,您需要继续初始化值并移动位以确定每次迭代的当前数字。由于您需要另一个标志,因此您需要使用另一个初始化为预期值的寄存器(我选择0
,通常代表false
)。
l3
(0
或1
)0
0
,那么它必须是1
。所以请记住,我们找到了1
,以后再打印,然后打印值和增量/循环。0
,请查看我们之前是否找到1
。如果是,则打印值并增加/循环。如果没有,那么递增/循环。对于实际打印,我不知道你在做什么。但是,您可以使用标签避免第二次比较。例如,当值ALWAYS_PRINT
时,将始终使用1
,因此您只需设置标记并立即打印1
,然后跳转到INCREMENT
。如果您这样做,那么PRINT_VALUE
只会用于打印0
,然后可以转到INCREMENT
。
从高级语言的角度来看,您需要:
int l2 = // value...
bool seenOneAlready = false;
if (l2 != 0)
{
// MSB first
for (int i = 31; i > -1; --i)
{
int l3 = (l2 >> i) & 1;
if (l3 == 1)
{
seenOneAlready = true;
printf("1");
}
else if (seenOneAlready)
{
printf("0");
}
}
}
else
{
printf("0");
}