如何确定有多少部分组成一个整数

时间:2014-03-04 21:11:57

标签: vb.net numbers match

对标题的措辞表示道歉,但确定如何说出来。

代码可能不只是描述。我已经删除了这个伪代码,试图传达我想要实现的目标。从下面的例子中我想要“Test1”和“test2”输出,但不是“test3”或“test4”

Dim DEBUG_LOGLEVEL_ALWAYSLOG As Integer = 0
Dim DEBUG_LOGLEVEL_INFORMATIONAL As Integer = 2
Dim DEBUG_LOGLEVEL_HIGHLEVEL As Integer = 4
Dim DEBUG_LOGLEVEL_MIDLEVEL As Integer = 8
Dim DEBUG_LOGLEVEL_LOWLEVEL As Integer = 16
Dim DEBUG_LOGLEVEL_SUBROUTINE As Integer = 32
Dim DEBUG_LOGLEVEL_FUNCTIONHIGHLEVEL As Integer= 64
Dim DEBUG_LOGLEVEL_FUNCTIONLOWLEVEL As Integer= 128

Dim DEBUG_LOGGING_LEVEL As Integer = DEBUG_LOGLEVEL_INFORMATIONAL+DEBUG_LOGLEVEL_HIGHLEVEL+DEBUG_LOGLEVEL_SUBROUTINE+DEBUG_LOGLEVEL_FUNCTIONHIGHLEVEL

Debug_AddLogEntry("Test1", DEBUG_LOGLEVEL_INFORMATIONAL)
Debug_AddLogEntry("Test2", DEBUG_LOGLEVEL_HIGHLEVEL)
Debug_AddLogEntry("Test3", DEBUG_LOGLEVEL_MIDLEVEL)
Debug_AddLogEntry("Test4", DEBUG_LOGLEVEL_SUBROUTINE)


Function Debug_AddLogEntry(text, loglevel)
    IF loglevel is contained within DEBUG_LOGGING_LEVEL
    'Code
Endif
End Function

1 个答案:

答案 0 :(得分:3)

你非常接近。首先,你会希望一切都是2的力量。你几乎拥有它,只需改变你的第一行。 0不是2的幂,但是1是:

Dim DEBUG_LOGLEVEL_ALWAYSLOG As Integer = 1

然后,对于您的调试功能,您可以使用按位运算来检查。

Function Debug_AddLogEntry(text, loglevel)
    IF (loglevel And DEBUG_LOGGING_LEVEL) = loglevel

只有当该位设置为1时才会返回true。

此外,您可以通过使用按位移位更改初始定义(更容易添加)。例如:

Dim DEBUG_LOGLEVEL_ALWAYSLOG As Integer = 1 << 0
Dim DEBUG_LOGLEVEL_INFORMATIONAL As Integer = 1 << 1
Dim DEBUG_LOGLEVEL_HIGHLEVEL As Integer = 1 << 2
Dim DEBUG_LOGLEVEL_MIDLEVEL As Integer = 1 << 3
...
etc