MIPS assembly - Reading from a file with hexadecim

2019-08-31 14:48发布

问题:

here is my question.

I want to read from a txt/dat file using MIPS assembly. Problem is that everyting in the file is hexadecimal such as 0x54ebcda7. When i try to read and load this into a register, MARS simulator reads it with the ascii values. I don't want this and need the "actual value" of that hexadecimal number? how do i do that?

回答1:

I'm just going to show how this could be done in C, which should be easy enough for you to translate into MIPS assembly:

// Assume that data from the file has been read into a char *buffer
// Assume that there's an int32_t *values where the values will be stored

while (bufferBytes) {
    c = *buffer++;
    bufferBytes--;

    // Consume the "0x" prefix, then read digits until whitespace is found
    if (c == '0' && prefixBytes == 0) {
        prefixBytes++;
    } else if (c == 'x' && prefixBytes == 1) {
        prefixBytes++;
    } else {
        if (c == ' ' || c == '\t' || c == '\n' || c == '\r') {
            if (prefixBytes == 2) {
                // Reached the end of a number. Store it and start over
                prefixBytes = 0;
                *values++ = currValue;
                currValue = 0;
            } else if (prefixBytes == 0) {
                // IGNORE (whitespace in between numbers)
            } else {
                // ERROR
            }
        } else if (prefixBytes == 2) {
            if (c >= '0' && c <= '9') {
                c -= '0';
            } else if (c >= 'a' && c <= 'f') {
                c -= ('a'-10);
            } else if (c >= 'A' && c <= 'F') {
                c -= ('A'-10);
            } else {
                // ERROR
            }
            currValue = (currValue << 4) | c;
        } else {
            // ERROR
        }
    }
}
// Store any pending value that was left when reaching the end of the buffer
if (prefixBytes == 2) {
    *values++ = currValue;
}