Best way to convert an ASCII digit to its numeric value

拟墨画扇 提交于 2021-01-29 07:20:32

问题


Lets say I have an ASCII character representing a decimal digit:

char digit;  // between 0x30 ('0') and 0x39 ('9') inclusive

I want to get the numeric value it represents (between 0 and 9). I am aware of two possible methods:

  1. subtraction:
    uint8_t value = digit - '0';
    
  2. bitwise and:
    uint8_t value = digit & 0x0f;
    

Which one is the most efficient in terms of compiled code size? Execution time? Energy consumption? As the answer may be platform-specific, I am most interested about the kind of architectures one may find in microcontrollers running low-power applications: Cortex-M, PIC, AVR, 8051, etc. My own test on an Arduino Uno seems to indicate that on AVR it doesn't make much of a difference, but I still would like to hear about other architectures.

Bonus questions: can either method be called “industry standard”? Are there situations where choosing the right one is essential?

Disclaimer: this is a followup to a discussion on an answer from arduino;stackexchange.com.


回答1:


You should compile it yourself.

int foo(char x)
{
    return x - '0';
}

int foo1(char x)
{
    return x & 0x0f;
}

char foo2(char x)
{
    return x - '0';
}

char foo3(char x)
{
    return x & 0x0f;
}

and the code

__tmp_reg__ = 0
foo(char):
        mov __tmp_reg__,r24
        lsl r0
        sbc r25,r25
        sbiw r24,48
        ret
foo1(char):
        andi r24,lo8(15)
        ldi r25,0
        ret
foo2(char):
        subi r24,lo8(-(-48))
        ret
foo3(char):
        andi r24,lo8(15)
        ret


来源:https://stackoverflow.com/questions/63862117/best-way-to-convert-an-ascii-digit-to-its-numeric-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!