単一のASCII文字を取得し、それをMIPで10進数に変換するにはどうすればよいですか?
ASCIIコードから特定の量を減算して10進表現にするために、いくつかの条件が必要ですか?
これは、Pax が書いたものの単純化された実装です (16 進数 - A から F は常に大文字であると想定しています)
ファイル hextodec.c
#include <stdio.h>
/*
*Converts an ASCII char to its decimal equivalent.
*Returns -1 on error.
*
*/
extern int hextodec(char* c);
int main(int argc,char **argv){
int i=0;
char digits[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','F'};
for (;i<16;i++){
printf("%c\t%d\n",digits[i],hextodec(digits+i));
}
return 0;
}
ファイル hextodec.S
#include <mips/regdef.h>
/* int hextodec(char* c)
* first (and only) argument is set in register a0.
* return value is set in register v0.
* function calling convention is ignored.
*/
.text
.globl hextodec
.align 2
.ent hextodec
hextodec:
lbu t0,0(a0) #load byte from argument
li t1,0X30
li t2,0x39
andi t1,t1,0x000000ff #Cast to word for comparison.
andi t2,t2,0x000000ff
bltu t0,t1,ERROR #error if lower than 0x30
bgt t0,t2,dohex #if greater than 0x39, test for A -F
addiu t0,t0,-0x30 #OK, char between 48 and 55. Subtract 48.
b return
dohex: li t1,0x41
li t2,0x46
andi t1,t1,0x000000ff #Cast to word for comparison.
andi t2,t2,0x000000ff
/*is byte is between 65 and 70?*/
bltu t0,t1,ERROR #error if lower than 0x41
bgt t0,t2,ERROR #error if greater than 0x46
ishex: addiu t0,t0,-0x37 #subtract 55 from hex char ('A'- 'F')
b return
ERROR: addiu t0,zero,-1 #return -1.
return: move v0,t0 #move return value to register v0
jr ra
.end hextodec
テスト走行
root@:~/stackoverflow# ./hextodec
0 0
1 1
2 2
3 3
4 4
5 5
6 6
7 7
8 8
9 9
A 10
B 11
C 12
D 13
E 14
F 15
root@:~/stackoverflow#
範囲内にあるかどうか、単一の 16 進文字をチェックする必要があります。
それ以外はエラーです。これらの範囲のいずれかに該当する場合は、次の手順を実行します。
10 進数以外の数字の文字が常に大文字であることが確実な場合は、上記の各リストの 3 番目の手順をスキップできますが、追加のコードをそれほど多く必要としません。
はい、ASCII 値から 48 を引くのがおそらく最も簡単でしょう。