Skip to content

Commit bd68bb0

Browse files
committed
COMMON: Added LSHIFT and RSHIFT bit shift operators
1 parent b671a13 commit bd68bb0

File tree

1 file changed

+32
-4
lines changed

1 file changed

+32
-4
lines changed

samples/distro-examples/libs/base64.bas

Lines changed: 32 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,12 @@ Export encode
99
const alphabet="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
1010
const padding="="
1111

12+
dim index(128)
13+
for i = 0 to 63
14+
index(asc(mid(alphabet, i + 1, 1))) = i
15+
next i
16+
index(asc(padding)) = 0
17+
1218
func encode(message)
1319
local result=""
1420
local in_len = len(message)
@@ -47,9 +53,25 @@ func encode(message)
4753
wend
4854
encode = result
4955
end
50-
56+
5157
func decode(message)
5258
local result = ""
59+
local in_len = len(message)
60+
local i, b_a, b_b, b_c, b_d
61+
62+
if (in_len % 4 != 0) then
63+
throw "Invalid base64 message length"
64+
endif
65+
66+
for i = 1 to in_len step 4
67+
b_a = index(asc(mid(message, i, 1)))
68+
b_b = index(asc(mid(message, i + 1, 1)))
69+
b_c = index(asc(mid(message, i + 2, 1)))
70+
b_d = index(asc(mid(message, i + 3, 1)))
71+
result += chr(((b_a lshift 2) + (b_b rshift 4)))
72+
result += chr(((b_b band 0xf) lshift 4) + (b_c rshift 2))
73+
result += chr(((b_c band 0x3) lshift 6) + b_d)
74+
next offset
5375
decode = result
5476
end
5577

@@ -66,9 +88,15 @@ sub test
6688
if (encode("This result will end with two equals.") != "VGhpcyByZXN1bHQgd2lsbCBlbmQgd2l0aCB0d28gZXF1YWxzLg==") then
6789
throw "base64 encoding error 3"
6890
endif
69-
' if (base64_dec("Zm9vYmEy") != "foobar") then
70-
' throw "base64 encoding error"
71-
' endif
91+
if (decode("Zm9vYmFy") != "foobar") then
92+
throw "base64 encoding error 4"
93+
endif
94+
if (decode("VGhpcyBpcyBhIGxvbmdlciBzdHJpbmc=") != "This is a longer string") then
95+
throw "base64 encoding error 5"
96+
endif
97+
if (decode("VGhpcyByZXN1bHQgd2lsbCBlbmQgd2l0aCB0d28gZXF1YWxzLg==") != "This result will end with two equals.") then
98+
throw "base64 encoding error 6"
99+
endif
72100
end
73101

74102
test

0 commit comments

Comments
 (0)