要创建一个存储为整数的新位串,请对每个位求和 2 的幂:
set bitint = (2**2) + (2**5) + (2**10)
write bitint
1060
要将现有位串中的位设置为 1,请使用 $zboolean 函数(逻辑 OR)的选项7 (arg1 ! arg2):
set bitint = $zboolean(bitint, 2**4, 7)
write bitint
1076
要将现有位串中的位设置为 0,请使用 $zboolean 函数的选项 2 (arg1 & ~arg2):
set bitint = $zboolean(bitint, 2**4, 2)
write bitint
1060
要在现有位串中切换位,请使用 $zboolean 函数(逻辑 XOR)的选项 6 (arg1 ^ arg2):
set bitint = $zboolean(bitint, 2**4, 6)
write bitint
1076
set bitint = $zboolean(bitint, 2**4, 6)
write bitint
1060
要将位字符串显示为整数,可以使用如下方法,该方法循环位并使用 $zboolean 函数:
Class Util.BitUtil Extends %RegisteredObject
{
/// w ##class(Util.BitUtil).LogicalToDisplay(1)
ClassMethod LogicalToDisplay(bitint As %Integer)
{
s str = ""
for i = 0 : 1 {
q:((2 ** i) > bitint)
if $zboolean(bitint, 2 ** i, 1) {
s str = str _ 1
} else {
s str = str _ 0
}
}
q str
}
}
DHC-APP>w ##class(Util.BitUtil).LogicalToDisplay(101000)
00010001010100011
此方法使用$Zlog函数将位字符串中的哪些位设置为整数,该函数返回以10为底的对数值。该方法删除越来越小的位串块,直到没有剩余:
/// w ##class(Util.BitUtil).FindSetBits(2)
ClassMethod FindSetBits(bitint As %Integer)
{
s bits = ""
while (bitint '= 0) {
s bit = $zlog(bitint) \ $zlog(2)
s bits = bit _ " " _ bits
s bitint = bitint - (2 ** bit)
}
q bits
}
DHC-APP>w ##class(Util.BitUtil).FindSetBits(3)
0 1
使用 $zboolean 函数对存储为整数的位串执行按位逻辑运算。
对于此示例,假设有两个位串 a 和 b,存储为整数,以及一个 LogicalToDisplay() 方法,如 Display Bits 中定义的,用于显示这些位。
do ##class(User.BitInt).LogicalToDisplay(a)
100110111
do ##class(User.BitInt).LogicalToDisplay(b)
001000101
使用 $zboolean 函数的选项 7 对位执行逻辑 OR:
set c = $zboolean(a, b, 7)
do ##class(User.BitInt).LogicalToDisplay(c)
101110111
使用 $zboolean 函数的选项 1 对位执行逻辑与:
set d = $zboolean(a, b, 1)
do ##class(User.BitInt).LogicalToDisplay(d)
000000101
要将存储为整数的位串转换为常规位串,请使用 $factor 函数。对于此示例,假设有一个位串为整数的 bitint 和一个 FindSetBits() 方法,如 Find Set Bits 中所定义,以显示设置了哪些位。
do ##class(User.BitInt).FindSetBits(bitint)
2 5 10
set bitstring = $factor(bitint)
zwrite bitstring
bitstring=$zwc(128,4)_$c(36,4,0,0)/*$bit(3,6,11)*/
请注意,常规位串中的位似乎向右移动了一位,因为位串没有位 0。位串中的第一位是位 1。