Trying to understand txt2bin code from forum
Posted: 23 Oct 2015, 04:10
For fun I decided to write some functions to convert text to binary and back. To do this I first learned how to read/write in binary. That was oddly the easy part. Now I want to understand how I can do it using code. I looked at existing code on the forum and selected these functions to learn from:
The problem is this code has elements I just don't understand. I can figure out in very general terms what the parts do, meaning the action they accomplish, but I have no idea exactly what they are doing or how they are doing it.
In the first function it is >> (8 - a_index) & 1) I am stumped on (I am not math literate). I know that >> is bitshift right, and & is bitwise-and, but knowing their names does not help me understand them.
In the second function the hardest part is x += x + (a_loopfield = "1") That is incrementing x by x +... Whatever that last bit is. That looks like it is assigning to a_loopfield, but a_loopfield is a built in variable and you can't assign to them, right? And what is = "1"? If it were := "1" I would say it was assigning a literal 1 character, but if I add : to it it breaks the code, so that's out. I have no reference point for that bit of code.
Anybody care to pick this code apart and explain it? I can't guarantee I will understand, but I promise to try
Code: Select all
text := "I have no idea why this works, but it obviously does."
bin := txt2bin(text)
msgbox % "Txt:`n" text "`n`nBin:`n" bin "`n`nTxt:`n" bin2txt(bin)
txt2bin(txt)
{
loop parse, txt
{
loop 8
{
bin := bin (asc(a_loopfield) >> (8 - a_index) & 1)
}
}
return bin
}
bin2txt(bin)
{
loop parse, bin
{
x += x + (a_loopfield = "1")
if !mod(a_index, 8)
{
txt := txt chr(x)
x = 0
}
}
return txt
}
In the first function it is >> (8 - a_index) & 1) I am stumped on (I am not math literate). I know that >> is bitshift right, and & is bitwise-and, but knowing their names does not help me understand them.
In the second function the hardest part is x += x + (a_loopfield = "1") That is incrementing x by x +... Whatever that last bit is. That looks like it is assigning to a_loopfield, but a_loopfield is a built in variable and you can't assign to them, right? And what is = "1"? If it were := "1" I would say it was assigning a literal 1 character, but if I add : to it it breaks the code, so that's out. I have no reference point for that bit of code.
Anybody care to pick this code apart and explain it? I can't guarantee I will understand, but I promise to try