问题描述
让我们说我有一个代表十进制数字的ASCII字符:
Lets say I have an ASCII character representing a decimal digit:
char digit; // between 0x30 ('0') and 0x39 ('9') inclusive
我想获取它表示的数值(在 0
和 9
之间).我知道两种可能的方法:
I want to get the numeric value it represents (between 0
and 9
).I am aware of two possible methods:
- 减法:
uint8_t value = digit - '0';
uint8_t value = digit & 0x0f;
就编译后的代码大小而言,哪一个是最有效的?执行时间处理时间?能源消耗?答案可能是特定于平台,我对架构的种类最感兴趣在运行低功耗应用的微控制器中可能会发现:Cortex-M,PIC,AVR,8051等.我自己的在Arduino Uno上进行测试似乎表明在AVR上并没有太大的区别,但是我仍然想听听其他架构.
Which one is the most efficient in terms of compiled code size?Execution time? Energy consumption? As the answer may beplatform-specific, I am most interested about the kind of architecturesone may find in microcontrollers running low-power applications:Cortex-M, PIC, AVR, 8051, etc. My own test on an Arduino Unoseems to indicate that on AVR it doesn't make much of a difference, butI still would like to hear about other architectures.
奖金问题:这两种方法都可以称为行业标准"吗?是在某些情况下,选择正确的选件至关重要?
Bonus questions: can either method be called "industry standard"? Arethere situations where choosing the right one is essential?
免责声明:这是讨论的后续内容.来自arduino; stackexchange.com的答案.
Disclaimer: this is a followup to a discussion on ananswer from arduino;stackexchange.com.
推荐答案
您应该自己编译.
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;
}
和代码
__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
这篇关于将ASCII数字转换为其数值的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!