布尔代数是硬件设计的基础,然而在软件算法设计中也有一席之地。比如从字符串到特定数字之映射,一般使用gperf来实现。
本文演示另外一种思路,就是用布尔代数来实现,以达到更高的效率。
A股字冠目前共有12种,分列如下:
000 0b0000,0000,0000
001 0b0000,0000,0001
002 0b0000,0000,0010
003 0b0000,0000,0011
300 0b0011,0000,0000
600 0b0000,0000,0000
601 0b0110,0000,0001
602 0b0110,0000,0010
603 0b0110,0000,0011
605 0b0110,0000,0101
688 0b0110,1000,1000
689 0b0110,1000,1001
我们看到需要低位的四位及高位的0位及2位共6位二进制数来确定一个字冠,如果将沪市低字节加上5,深市高字节的低位移动到低字节的第二位,则可以用四个二进制位唯一标记一个字冠。
000 0000
001 0001
002 0010
003 0011
300 0100
600 0101
601 0110
602 0111
603 1000
605 1010
688 1101
689 1110
将此结果映射到0~15后,得到四个卡诺图,化简后得到四个逻辑函数如下:
c++测试代码如下:
#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
inline int get_hdr_idx_by_bitop(const int code);
inline int get_hdr_idx_by_bool(const int code);
char hdrs[][8] =
{
"000",
"001",
"002",
"003",
"300",
"600",
"601",
"602",
"603",
"605",
"688",
"689"
};
int main(void)
{
for(int ii=0; ii<12; ++ii)
{
auto hdrptr = hdrs[ii];
int securitycode = strtol(hdrptr, nullptr, 16);
int idx1 = get_hdr_idx_by_bitop(securitycode);
int idx2 = get_hdr_idx_by_bool(securitycode);
printf("hdr[%d,%d]=%06x\n", idx1, idx2, securitycode);
}
exit(0);
}
int get_hdr_idx_by_bitop(const int code)
{
int a;
a = 0xf & code;
int h0 = (code >> 8) & 1;
int h2 = (code >> 10) & 1;
int l2 = (code >> 2) & 1;
int l3 = (code >> 3) & 1;
a += (((h0 | h2) << (2-l3)) | (h2 ^ (l2 ^ l3)));
return a;
}
int get_hdr_idx_by_bool(const int code)
{
int a, b, c, d, e;
a = 0xf & code;
int h0 = (code >> 8) & 1;
int h2 = (code >> 10) & 1;
a += ((h0 | h2) << 2) | h2;
d = a & 1; a >>= 1;
c = a & 1; a >>= 1;
b = a & 1; a >>= 1;
e = ~a;
return ((a << 3)
| ((e & b) << 2)
| (((a | c) & (e | b)) << 1)
| ((a | d) & (e | c)));
}