How would you go about converting a stored Hex value to it's binary equivalent using lc3/assembly code?

Pené David II picture Pené David II · Sep 12, 2012 · Viewed 7.1k times · Source

The values are stored in a .BLKW object and are loaded in a LOOP with LDR R0,R1,0 - ADD R1,R1,1 (to increment the .BLKW address). The problem is how do you convert the stored HEX values to their binary values, and then output the conversion to the CONSOLE in 16-bit binary format. Any ideas will be greatly appreciated! I've thought about ANDing values, but am unsure how to go about it.

Answer

Remption picture Remption · Dec 6, 2013

You've already got the loop down. However, one small error.
We know that when we use OUT to print, it prints the value in R0 to the console. So, the number we're printing (the number in R0) should always be 0 or 1. Thus, the hex value we're working on should be stored in some other register, like R2. So, the code "LDR R0, R1, 0" becomes "LDR R2, R1, 0".

Now, for each word (aka address in the .BLKW) you have to convert it to binary, printing one bit at a time.

You could do 16 AND operations. Check if the [16] (the left-most bit) is one by ANDing R2 with the number with 1000 0000 0000 0000. If the result isn't 0, then you know the left-most bit is a 1, so print 1. If the result is 0, you know it must be zero, so print 0. Then AND R2 with 0100 0000 0000 0000 to check the second bit in the same manner and so forth.

However, that's just messy. The best way is to use a loop.

Set one of the registers - let's say R3, to 1000 0000 0000 0000. We'll be using this in a minute.

Let's use R5 as our sentinel, aka "counter", to tell us when we've processed all 16 digits. We'll set R5 to 16, then subtract 1 from R5 each time we go through the loop, and when we hit 0, we'll exit the loop.

Now, what to put inside the loop.

For each iteration, AND R2 and R3, and store the result in some unused register like R4. If the result is zero, we know the left-most bit of R2 is zero, so print 0. If the result is negative (because 1000 0000 0000 0000 is a 2's complement number and thus negative), we know the left-bit is a 1, so print 1.

Then do a left bit-wise shift in R2. This is accomplished by adding R2 to itself and storing it via: "ADD R2, R2, R2".

Decrement our counter in R5 via : "ADD R5, R5, #-1"

Return to the start of the loop.

The result should be what you need.