解码十六进制数字的最快方法 [英] Fastest way to decode a hexadecimal digit

查看:472
本文介绍了解码十六进制数字的最快方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找获取十六进制ASCII字符十进制值的最快方法,即保证在以下字符串中出现的十进制值(可以是小写或大写,但不能有空格):

I am looking for the fastest way to get the decimal value of a hexadecimal ASCII character, i.e. one that is guaranteed to appear in the following string (it can be lower or upper case, but no white space):

0123456789ABCDEFabcdef

到目前为止,我想出的最好的公式是:

So far, the best formula I've come up with is:

char c = 'd';  // or any other hex character
int value = (((c & 0x1F) + 9) % 25;

请注意,它是无分支的,但确实包含昂贵的模运算.

Note that it is branch-free, but it does contain an expensive modulo operation.

我可以做得更好吗?

推荐答案

(d & 0xf) + ((d & 0x40) >> 3) + ((d & 0x40) >> 6)

非常简单的摆弄.

演示

一个略有不同的变体

(d & 0xf) + (d >> 6) + ((d >> 6) << 3)

保存另一个按位and操作.

两个变体基本上将6位乘以9(与Mark Ransom的答案相同,但没有硬件乘法).

Both variants basically multiply the 6th bit by 9 (same as in the Mark Ransom's answer but without hardware multiplication).

这篇关于解码十六进制数字的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆