I'm a beginner to MIPS. I'm trying to figure out converting user's inputted hexadecimal values into 32-bit binary number, and store it to an array. Here's what I think: For example, the number is (3ABCD123), then I read this value and split every character and put it in a string array. Then, for every value in the array, convert it to a 4-bit binary number and store it to another array. But I am stuck on splitting the user's inputted string into every character and store it in an array. Please give any suggestions or help, thanks!
1 Answers
MARS / SPIM have a string-input system call. A string is a char array; you don't have to manually "split" anything until you're looping over the input buffer with lbu
. (Unfortunately the system-call doesn't return the length, leaving you to scan the buffer for a terminating 0
byte, or just write your loop to stop on the first non-hexdigit character instead of using a counter.)
Then you'll want to validate the input to check it's a hex digit, and calculate a 4-bit integer.
A hex digit is either a decimal digit '0'..'9'
or 'a'..'f'
, maybe after folding upper-case to lower-case, so it will take some branching and subtraction to do either
digit = c - '0'
or digit = lcase(c) - 'a'
as appropriate.
You don't want to store separate 4-bit values in any array; shift + OR them into a 32-bit register to build up the final 32-bit integer. Only once you have that should you store the whole word into an array and read another string.
(MIPS is byte-addressable so you could store in chunks of 2 nibbles, but it's not sub-byte addressable so you can't sb
8 separate nibbles into 4 bytes and lw
a complete 32-bit word.)
Shift/or into a register like total = (total<<4) | digit
works even if the string of hex digits is fewer than 8 digits, assuming you zero the total
to start with. The first (most-significant) ends up shifted to wherever its place value actually is, i.e. by the number of digits following it. Since you're shifting in a register, not messing around with memory, endianness doesn't enter into it. And numbers as strings of digits are always most-significant first, because that's the convention in most human writing systems that use Arabic numerals. (like 1234).

- 328,167
- 45
- 605
- 847
-
(This isn't a very detailed answer; it was going to be a comment until I realized it is technically an answer. I think it addresses the parts of the question that are explicitly on the wrong track, even though it doesn't go into much detail about how to do the right way. There are other Q&As about looping over strings on Stack Overflow, and probably even about hex->integer on MIPS; search for them if you want code.) – Peter Cordes Nov 10 '19 at 09:12