Oracle PL / SQL – BITAND関数の例
BITAND
関数は、入力と出力をビットのベクトルとして扱い、出力は入力のビット単位のANDです。
基本的に、以下の手順を実行します。
-
入力をバイナリに変換します。
-
これら2つの文字列に対して標準のビット単位のAND演算を実行します。
-
バイナリの結果を10進数に変換し、値を返します。
1. BITANDの例
SELECT BITAND (12,10) FROM DUAL; -- output 8 1 1 0 0 = 12 1 0 1 0 = 10 ------------- 1 0 0 0 = 8
SELECT BITAND(24,18) FROM DUAL; -- output 16 1 1 0 0 0 = 12 1 0 0 1 0 = 18 ------------- 1 0 0 0 0 = 16
Note
これを試してください–Binary
to Decimal converter
2. BITANDを使用してトランザクションステータスを計算します。
2.1 In this example suppose txn_details
table contains transaction details of some payment gateway with different banks. ここで、txn_details
テーブルのtxn_status
列には単一の数値が含まれていますが、この値の各ビット内にはいくつかの意味があります。
txn_status
の意味を次のように考えました
-
バイナリ値001(10進数1)は、銀行に送信された要求を意味します。
-
バイナリ値010(10進数2)は、受信した応答を意味します。
-
バイナリ値100(10進数の4)は、応答で受信したエラーを意味します。
CREATE TABLE txn_details ( TXN_ID number(5) primary key, BANK_NAME varchar2(20), TXN_STATUS number(1) );
2.2 Inserting sample values.
INSERT INTO txn_details VALUES (1,'ABC Bank',3); INSERT INTO txn_details VALUES (2,'National Bank',0); INSERT INTO txn_details VALUES (3,'Corporation Bank',1); INSERT INTO txn_details VALUES (4,'ABC Bank',7);
2.3 The example uses the DECODE
function to provide two values for each of the three bits in the txn_status
value, one value if the bit is turned on and one if it is turned off.
REQ_SENT
列の場合、BITANDは最初にtxn_status
を1(バイナリ001)と比較します。 有効なビット値のみが比較されるため、右端のビットに1が含まれるバイナリ値はすべて肯定的に評価され、1を返します。
偶数は0を返します。 DECODE
関数は、BITANDによって返される値を1と比較します。 両方が1の場合、REQ_SENT
の値は「YES」です。それ以外の場合は「NO」です。
他の2つの列RESPONSE_RECEIVED
とERROR_IN_RESPONSE
も同様に評価されました。
SELECT txn_id,bank_name,txn_status , DECODE(BITAND(txn_status, 1), 1, 'YES', 'NO') "REQ_SENT", DECODE(BITAND(txn_status, 2), 2, 'YES', 'NO') "RESPONSE_RECEIVED", DECODE(BITAND(txn_status, 4), 4, 'YES', 'NO') "ERROR_IN_RESPONSE" FROM txn_details;
出力
TXN_ID | 銀行名 | TXN_STATUS | REQ_SENT | RESPONSE_RECEIVED | ERROR_IN_RESPONSE |
---|---|---|---|---|---|
1 |
ABCバンク |
3 |
YES |
YES |
NO |
2 |
国営銀行 |
0 |
NO |
NO |
NO |
3 |
株式会社バンク |
1 |
YES |
NO |
NO |
4 |
ABCバンク |
7 |
YES |
YES |
YES |