Converting one language (ASCII, Binary, B64, etc) to another

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
GameNtt
Posts: 154
Joined: 19 Aug 2022, 03:36

Converting one language (ASCII, Binary, B64, etc) to another

Post by GameNtt » 26 Nov 2022, 07:51

I want help to Improve my function to convert from Binary to ASCII and ASCII to Binary. I am aware of other functions but they aren't exactly what I want.

In the function for Binary to ASCII, a "word" is extracted, the length of the "word" extracted is found, zeroes are added till the length equals 7, two variables, power and output are declared with the values of 6 and 0 respectively, a loop is run seven times, in which only first digit extracted with SubStr is multiplied with (2 to the power of %power%) and added to output, value of power is decreased by one and next digit is then extracted and then repeat all the above steps. This entire thing runs for the number of "words" there are. Over here "word" refers to one sequence of bits corresponding to one character (1111111 (del) is one example, 0100001(A) is another example). I don't know how to check the number of "words" in the input string or how to extract a "word" in this function.
My psuedo-code for this is

Code: Select all

BintoASC(input)
{
    ;idk how to find the number of sequences of bits and how to take each individual sequence of bits as input so ill assume that in2 is the word extracted and input is the input
    in2 := input
    lenw := StrLen(in2)
    OutputDebug, The value of lenw is %lenw%
    while(lenw<7)
    {
        in2 := 0 . in2
        lenw++
        OutputDebug, The value of lenw is %lenw%
    }
    OutputDebug, The value of lenw is %lenw%
    power := 6
    output := 0
    pos := 1
    loop 7
    {
        val := SubStr(in2, %pos%, 1)
        output2 := val * (2**%power%)
        output := %output% + %output2%
        power--
        pos++
        OutputDebug, In Binary to ASCII, The value of val is %val%, the value of output2 is %output2%, the value of output is %output%, the value of power is %power%, the value of pos is %pos%.
    }
    outputchr := Chr(%output%)
    outputstr := outputstr . outputchr
    ; this would be where the loop ends
    OutputDebug, The final value is %outputstr%, the final character is %outputchr%.
}
For BintoASC, the problems that I am facing right now are that %val% is always 1 thereby making the final value what is expected.

Now for the inverse function, ASCII to binary, a letter is extracted, it is converted to decimal (Asc()) and stored in a variable num, two variables power and output are declared with the values of 6 and no initial value (output :=) respectively, a loop is run 7 times, in which if (num>(2^%power%)), the output digit is 1, else it is 0, the output digit is then concatenated with output and the value of power is decreased by one. After the loop runs, a space is given to ensure distinction between two sequences for two characters. This entire thing runs in a loop which runs for the number for characters in the input string.
My psuedo-code for this is

Code: Select all

ASCtoBin(input)
{
    lenstr := StrLen(input)
    output := 
    power := 6
    in2 := ""
    pos := 0
    OutputDebug, %lenstr%
    Loop, %lenstr%
    {
        in2 := SubStr(input, %pos%, 1)
        in3 := Asc(in2)
        loop 7
        {
            if(in3>(2^(%power%)))
            output := output . 1
            Else
            output := output . 0
            power--
            pos++
            OutputDebug, In ASCII to Binary, The value of in2 is %in2%, the value of in3 is %in3%, the value of output is %output%, the value of power is %power%, the value of pos is %pos%.            
        }
    }
}
For ASCtoBin, the problems that I am facing right now are that %in2% is always A thereby making the final result as 1111111.

The aforementioned problems occur when I activate this hotkey which is used to troubleshoot and find what's wrong and what needs changing.

Code: Select all

!+t::
val := BintoASC(100001)
OutputDebug, %val%
val2 := ASCtoBin("A")
OutputDebug, %val2%
Return
Thanks a lot in advance.

Edit - Here's a pastebin link with the entire file contents which will be updated each subsequent post by me with the changes made written in a documentation comment at the beginning of the pastebin - https://pastebin.com/4dMwYfPf.
Last edited by GameNtt on 26 Nov 2022, 09:24, edited 1 time in total.

User avatar
mikeyww
Posts: 26885
Joined: 09 Sep 2014, 18:38

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by mikeyww » 26 Nov 2022, 08:19

I'm not sure if you are referring to bytes.

Does this help?

Code: Select all

binary = 00100001
MsgBox, 64, Result, % binary "`n`nDecimal = " bin2dec(binary)

bin2dec(binary) { ; Binary number => Decimal number
 len := StrLen(binary)
 Loop, Parse, binary
  dec += 2 ** (len - A_Index) * A_LoopField
 Return dec
}
SubStr(in2, %pos%, 1)
Functions use expressions. This usually means no %.
Variable names in an expression are not enclosed in percent signs (except for pseudo-arrays and other double references).
Explained: A_Index
The built-in variable A_Index contains the number of the current loop iteration.

GameNtt
Posts: 154
Joined: 19 Aug 2022, 03:36

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by GameNtt » 26 Nov 2022, 09:18

mikeyww wrote: I'm not sure if you are referring to bytes.

Does this help?

Code: Select all

binary = 00100001
MsgBox, 64, Result, % binary "`n`nDecimal = " bin2dec(binary)

bin2dec(binary) { ; Binary number => Decimal number
 len := StrLen(binary)
 Loop, Parse, binary
  dec += 2 ** (len - A_Index) * A_LoopField
 Return dec
}
I guess that partially helps. It helps only if the given string is only one 7-bit sequence. For my purposes, I am using 7-bit, not 8-bit. How would I implement that? And what would this function's inverse function? Would it be possible to do it in a similar manner?

User avatar
mikeyww
Posts: 26885
Joined: 09 Sep 2014, 18:38

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by mikeyww » 26 Nov 2022, 09:27

You can parse a longer word if needed.

Code: Select all

b = 0100001
c = 0010010
binary := b c
Loop, % StrLen(binary) / 7
 MsgBox, 64, Result, % bin2dec(SubStr(binary, (A_Index - 1) * 7 + 1, 7))

bin2dec(binary) { ; Binary number => Decimal number
 len := StrLen(binary)
 Loop, Parse, binary
  dec += 2 ** (len - A_Index) * A_LoopField
 Return dec
}
See if you can get this part working before proceeding to the next!

You can always cheat and check someone else's answer key.

https://www.autohotkey.com/board/topic/46221-decimal-to-binary-and-vice-versa-script-help/

https://www.autohotkey.com/board/topic/49990-binary-and-decimal-conversion/

GameNtt
Posts: 154
Joined: 19 Aug 2022, 03:36

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by GameNtt » 26 Nov 2022, 10:19

The problem with dividing by seven is that it assumes that all the sequences are of 7 bits. What if the external converter converts it without a 0 in the beginning making the sequence shorter and then subsequently making the entire thing fail?

User avatar
mikeyww
Posts: 26885
Joined: 09 Sep 2014, 18:38

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by mikeyww » 26 Nov 2022, 10:21

If you have a long string of digits, you will need a way to understand and describe how to parse them. If you have no idea how to do it, then your coding will take a very long time!

garry
Posts: 3764
Joined: 22 Dec 2013, 12:50

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by garry » 26 Nov 2022, 10:50

A collection of small (maybe useful) ahk functions from user @jNizM
viewtopic.php?f=6&t=3514

Code: Select all

;A collection of small (maybe useful) ahk functions from user [mention]jNizM[/mention] 
;-- https://www.autohotkey.com/boards/viewtopic.php?f=6&t=3514
;-
;- HEX2ASCII  example
;- 1A is EOF
bb:="48656C6C6F204741525259202E20486F772061726520796F753F0D4E65776C696E652D32202D41424344450D454E440D0A1A"
i=0
loop,parse,bb
{
i++
y:=a_loopfield
M:=mod(i,2)
if m=0
  e .= "0x" . z . y . " "
z:=y
}
;msgbox,%e%
ee:=HexToStr(e)
msgbox,%ee%
MsgBox % "Hex:`t0x41 0x75 0x74 0x6F 0x48 0x6f 0x74 0x6b 0x65 0x79`nASCII:`t" hexToStr("0x41 0x75 0x74 0x6F 0x48 0x6f 0x74 0x6b 0x65 0x79")

;return

hexToStr(hex)
{
    static u := A_IsUnicode ? "_wcstoui64" : "_strtoui64"
    loop, parse, hex, " "
    {
        char .= Chr(DllCall("msvcrt.dll\" u, "Str", A_LoopField, "Uint", 0, "UInt", 16, "CDECL Int64"))
    }
    return char
}
;MsgBox % "Hex:`t0x41 0x75 0x74 0x48 0x6f 0x74 0x6b 0x65 0x79`nHex:`t" hexToStr("0x41 0x75 0x74 0x48 0x6f 0x74 0x6b 0x65 0x79")
;=======================================================================

;-- https://www.autohotkey.com/boards/viewtopic.php?p=17835#p17835
MsgBox, % "Decimal:`t`t42`n"
        . "to Binary:`t`t"      ConvertBase(10, 2, 42)       "`n"
        . "to Octal:`t`t"       ConvertBase(10, 8, 42)       "`n"
        . "to Hexadecimal:`t"   ConvertBase(10, 16, 42)      "`n`n"
        . "Hexadecimal:`t2A`n"
        . "to Decimal:`t"       ConvertBase(16, 10, "2A")    "`n"
        . "to Octal:`t`t"       ConvertBase(16, 8, "2A")     "`n"
        . "to Binary:`t`t"      ConvertBase(16, 2, "2A")     "`n`n"
ExitApp


ConvertBase(InputBase, OutputBase, nptr)
{
    static u := A_IsUnicode ? "_wcstoui64" : "_strtoui64"
    static v := A_IsUnicode ? "_i64tow"    : "_i64toa"
    VarSetCapacity(s, 66, 0)
    value := DllCall("msvcrt.dll\" u, "Str", nptr, "UInt", 0, "UInt", InputBase, "CDECL Int64")
    DllCall("msvcrt.dll\" v, "Int64", value, "Str", s, "UInt", OutputBase, "CDECL")
    return s
}
;=====================================================================

GameNtt
Posts: 154
Joined: 19 Aug 2022, 03:36

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by GameNtt » 26 Nov 2022, 11:17

mikeyww wrote: If you have a long string of digits, you will need a way to understand and describe how to parse them. If you have no idea how to do it, then your coding will take a very long time!
Would it be possible to extract the characters in between two spaces and then use that as the input? Then the number of times the loop would be run would be the number of spaces in the entire string (excluding one at the end if there is one at the end) + 1.

User avatar
mikeyww
Posts: 26885
Joined: 09 Sep 2014, 18:38

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by mikeyww » 26 Nov 2022, 11:24

Code: Select all

binary := "   0100001   0010010            "
For each, word in StrSplit(Trim(binary), " ")
 If (word > "")
  MsgBox, 64, Result, % bin2dec(word)

bin2dec(x) { ; https://www.autohotkey.com/board/topic/49990-binary-and-decimal-conversion/
 Return (StrLen(x) > 1 ? bin2dec(SubStr(x, 1, -1)) << 1 : 0) | SubStr(x, 0)
}

GameNtt
Posts: 154
Joined: 19 Aug 2022, 03:36

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by GameNtt » 26 Nov 2022, 12:09

mikeyww wrote:
26 Nov 2022, 11:24

Code: Select all

binary := "   0100001   0010010            "
For each, word in StrSplit(Trim(binary), " ")
 If (word > "")
  MsgBox, 64, Result, % bin2dec(word)

bin2dec(x) { ; https://www.autohotkey.com/board/topic/49990-binary-and-decimal-conversion/
 Return (StrLen(x) > 1 ? bin2dec(SubStr(x, 1, -1)) << 1 : 0) | SubStr(x, 0)
}
This works great. How about the inverse of this though?

User avatar
mikeyww
Posts: 26885
Joined: 09 Sep 2014, 18:38

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by mikeyww » 26 Nov 2022, 12:14

I would go by the answer key already cited (twice)!

teadrinker
Posts: 4326
Joined: 29 Mar 2015, 09:41
Contact:

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by teadrinker » 26 Nov 2022, 12:19

@GameNtt

Code: Select all

MsgBox, % bin7 := ASCIItoBin7("AutoHotkey")
MsgBox, % Bin7toASCII(bin7)

ASCIItoBin7(asciiStr) {
   bin7 := ""
   Loop, parse, asciiStr
   {
      ascii := Asc(A_LoopField)
      if (ascii > 127)
         continue
      b := ""
      Loop 7
         b := (ascii >> (A_Index - 1)) & 1 . b
      bin7 .= b . " "
   }
   Return RTrim(bin7)
}

Bin7toASCII(bin7) {
   asciiStr := ""
   while RegExMatch(RegExReplace(bin7, "[^10]"), "O)[10]{7}", m, m ? m.Pos + m.Len : 1) {
      ascii := 0
      Loop 7
         ascii |= SubStr(m[0], A_Index, 1) << 7 - A_Index
      asciiStr .= Chr(ascii)
   }
   Return asciiStr
}
I suppose you need something like this?

GameNtt
Posts: 154
Joined: 19 Aug 2022, 03:36

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by GameNtt » 26 Nov 2022, 12:25

mikeyww wrote:I would go by the answer key already cited (twice)!
I found the function, just how would I implement it for each character is what I mean.
The function in question being

Code: Select all

Dec(x){
	return (StrLen(x)>1 ? Dec(SubStr(x,1,-1))<<1:0)|SubStr(x,0)
}

GameNtt
Posts: 154
Joined: 19 Aug 2022, 03:36

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by GameNtt » 26 Nov 2022, 12:32

teadrinker wrote:
26 Nov 2022, 12:19
@GameNtt

Code: Select all

MsgBox, % bin7 := ASCIItoBin7("AutoHotkey")
MsgBox, % Bin7toASCII(bin7)

ASCIItoBin7(asciiStr) {
   bin7 := ""
   Loop, parse, asciiStr
   {
      ascii := Asc(A_LoopField)
      if (ascii > 127)
         continue
      b := ""
      Loop 7
         b := (ascii >> (A_Index - 1)) & 1 . b
      bin7 .= b . " "
   }
   Return RTrim(bin7)
}

Bin7toASCII(bin7) {
   asciiStr := ""
   while RegExMatch(RegExReplace(bin7, "[^10]"), "O)[10]{7}", m, m ? m.Pos + m.Len : 1) {
      ascii := 0
      Loop 7
         ascii |= SubStr(m[0], A_Index, 1) << 7 - A_Index
      asciiStr .= Chr(ascii)
   }
   Return asciiStr
}
I suppose you need something like this?
Exactly what I wanted. Thanks!!

GameNtt
Posts: 154
Joined: 19 Aug 2022, 03:36

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by GameNtt » 29 Nov 2022, 09:04

Thanks for all of your help for variations on my functions. Going back to my original functions, for some reason, now the val part in the first function (bin2asc) is working properly, but neither output1 or output2 is working in any manner intended, except for the final iteration where output2 is giving a correct value of either 1 or 0 depending on the last character in the input. If anyone could tell why it is so, I would be grateful.

Code: Select all

BintoASC(input)
{
    ;idk how to find the number of sequences of bits and how to take each individual sequence of bits as input so ill assume that in2 is the word extracted and input is the input
    in2 := input
    lenw := StrLen(in2)
    OutputDebug, The value of lenw is %lenw%
    while(lenw<7)
    {
        in2 := 0 . in2
        lenw++
        OutputDebug, The value of lenw is %lenw%
    }
    OutputDebug, The value of lenw is %lenw%
    power := 6
    output := 0
    pos := 1
    loop 7
    {
        val := SubStr(in2, pos, 1)
        output2 := val * (2**%power%)
        output := %output% + %output2%
        power--
        pos++
        OutputDebug, In Binary to ASCII, The value of val is %val%, the value of output2 is %output2%, the value of output is %output%, the value of power is %power%, the value of pos is %pos%.
    }
    outputchr := Chr(%output%)
    outputstr := outputstr . outputchr
    ; this would be where the loop ends
    OutputDebug, The final value is %outputstr%, the final character is %outputchr%.
}

User avatar
mikeyww
Posts: 26885
Joined: 09 Sep 2014, 18:38

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by mikeyww » 29 Nov 2022, 09:42

Expressions:
Variable names in an expression are not enclosed in percent signs (except for pseudo-arrays and other double references).

GameNtt
Posts: 154
Joined: 19 Aug 2022, 03:36

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by GameNtt » 29 Nov 2022, 10:18

mikeyww wrote:
29 Nov 2022, 09:42
Expressions:
Variable names in an expression are not enclosed in percent signs (except for pseudo-arrays and other double references).
Thank you. Is it necessary for the input being given to the function has to be a string if you are using StrTrim? What if I give 1000001 1000010 as input? What would happen?

User avatar
mikeyww
Posts: 26885
Joined: 09 Sep 2014, 18:38

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by mikeyww » 29 Nov 2022, 11:04

Script authors need not ask what will happen if they run their script. They can just run their script instead, and find out.

A function can accept any expression. Documentation describes it.
Expressions are combinations of one or more values, variables, operators and function calls. For example, 10, 1+1 and MyVar are valid expressions. Usually, an expression takes one or more values as input, performs one or more operations, and produces a value as the result. The process of finding out the value of an expression is called evaluation. For example, the expression 1+1 evaluates to the number 2.

GameNtt
Posts: 154
Joined: 19 Aug 2022, 03:36

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by GameNtt » 29 Nov 2022, 11:56

Thank you everyone for your contributions. I have edited the pastebin with the finalized version of BintoASC and ASCtoBin. Now my next function is ASCII to B64 and B64 to ASCII via binary. For this, I would require an 8-bit version of the BintoASC and ASCtoBin functions, but that can be done quite simply. In B64, 6-bit segments of binary are used. All 64 possible values have an equivalent character, and = is used as padding and represents 00. All the characters are converted to their 8-bit binary equivalents, whitespaces are removed, then whitespaces are inserted every 6 characters. If the total number of character given as input is not divisible by 3, 00 (represented by =) is used as many times are it is required to make the entire set of binary characters (not including whitespaces) divisible by 24. After that step, all the 6-bit sequences are converted to their B64 equivalents. Could anyone help me make the B64 part of the function? I would like to stick with the standard B64 (RFC 4648) except for the last two, which would be . (fullstop/period) as 62(111110) and - (hyphen) as 63(111111). I am ok with calling the 8-bit function (BintoASC8 and ASCtoBin8) within this function. Thank you :)

teadrinker
Posts: 4326
Joined: 29 Mar 2015, 09:41
Contact:

Re: Converting one language (ASCII, Binary, B64, etc) to another

Post by teadrinker » 29 Nov 2022, 12:04

To convert binary data to Base64, the CryptBinaryToString function is used. Look for examples on this forum.

Post Reply

Return to “Ask for Help (v1)”