Jump to content
BinaryBrother

ConsoleWrite is converting binary to string

Recommended Posts

BinaryBrother

Here is my code. Adopted from a post UEZ made.

_GenerateUID()
Func _GenerateUID()
    Local $lReturn, $lDriveSerial,$lRandomSeed = ""
    Local $lChr[2]
    For $N = 1 To 32
        $lChr[0] = Chr(Random(65, 90, 1)) ;A-Z
        $lChr[1] = Chr(Random(48, 57, 1)) ;0-9
        $lRandomSeed &= $lChr[Random(0, 1, 1)]
    Next
    $lDriveSerial = DriveGetSerial(StringLeft(@WindowsDir, 3))
    $lReturn = StringToBinary($lRandomSeed & $lDriveSerial)
    ConsoleWrite($lReturn) ;<--- Is printed as a String.
    ConsoleWrite(@CRLF & $lReturn & @CRLF) ;<--- Printed properly as Binary?
    Return $lReturn
EndFunc   ;==>_GenerateUID

Output:

--> Press Ctrl+Alt+Break to Restart or Ctrl+Break to Stop
V9P03Y144OZW38YC80IW1IJXWH4003501486415223
0x5639503033593134344F5A57333859433830495731494A58574834303033353031343836343135323233
+>10:40:52 AutoIt3.exe ended.rc:0
+>10:40:52 AutoIt3Wrapper Finished.
>Exit code: 0    Time: 0.544


Whenever ConsoleWrite is fed pure binary, it will output it as a string. Whenever a string is mixed with the binary, it outputs the binary as binary.

I found this especially confusing when I consulted the Help Documents for an answer...

Binary data is written as-is. It will not be converted to a string. To print the hex representation of binary data, use the String() function to explicitly cast the data to a string.

 

I'm sure I'm missing something, as usual. As always, thanks for your time! ^_^

Edited by BinaryBrother

Share this post


Link to post
Share on other sites
UEZ

Seems to be a bug. Once something different than the variable is executed the string becomes a binary string.

Edited by UEZ

Please don't send me any personal message and ask for support! I will not reply!

Selection of finest graphical examples at Codepen.io

The own fart smells best!
Her 'sikim hıyar' diyene bir avuç tuz alıp koşma!
¯\_(ツ)_/¯  ٩(●̮̮̃•̃)۶ ٩(-̮̮̃-̃)۶ૐ

Share this post


Link to post
Share on other sites
jchd

There is no bug here: MyFunc($BinaryVar) operates on the binary variable passed, but MyFunc("abc" & $BinaryVar) operates on the result of the expression, where the & operator forces conversion of $BinaryVar to a string, hence MyFunc is passed a string in this case.

ConsoleWrite is no different, except that it also converts AutoIt (Unicode) strings to ANSI and this causes non-Ansi characters to be replaced by question marks.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites
BrewManNH

There's a track ticket about this issue #2688.


If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Share this post


Link to post
Share on other sites
BinaryBrother

There is no bug here: MyFunc($BinaryVar) operates on the binary variable passed, but MyFunc("abc" & $BinaryVar) operates on the result of the expression, where the & operator forces conversion of $BinaryVar to a string, hence MyFunc is passed a string in this case.

ConsoleWrite is no different, except that it also converts AutoIt (Unicode) strings to ANSI and this causes non-Ansi characters to be replaced by question marks.

The only thing is, it converts the binary to a string without using the '&' operator. The below is outputting a string to the console, despite being binary.

$Test = StringToBinary(DriveGetSerial("C:\"))
ConsoleWrite($Test)

Since ConsoleWrite is being fed binary and does not convert binary to string, should it not output binary?

Edited by BinaryBrother

Share this post


Link to post
Share on other sites
jchd

From the specification of ConsoleWrite in the help file, no!

At the end of the day what we experience here is perfectly logical and conform, relative to specifications. That it may not directly fit somebody (you, me, anyone) today's or tomorrow's need is a complete different matter. Anyway, it's very easy to make it output exactly what's wanted, one way or the other.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites
BinaryBrother

This example just confuses me, so I'm going to stop poking the binary bear...

$Test = Binary(0x00204060)
ConsoleWrite("String: ")
ConsoleWrite($Test)
ConsoleWrite(@CRLF)
ConsoleWrite("Binary: " & $Test & @CRLF)
ConsoleWrite("MORE OUTPUT" & @CRLF)
ConsoleWrite("MORE OUTPUT" & @CRLF)
ConsoleWrite("MORE OUTPUT" & @CRLF)
ConsoleWrite("MORE OUTPUT" & @CRLF)
ConsoleWrite("MORE OUTPUT" & @CRLF)
ConsoleWrite("MORE OUTPUT" & @CRLF)
ConsoleWrite("MORE OUTPUT" & @CRLF)
ConsoleWrite("MORE OUTPUT" & @CRLF)
ConsoleWrite("MORE OUTPUT" & @CRLF)
ConsoleWrite("MORE OUTPUT" & @CRLF)
ConsoleWrite("MORE OUTPUT" & @CRLF)
ConsoleWrite("MORE OUTPUT" & @CRLF)
ConsoleWrite("MORE OUTPUT" & @CRLF)
ConsoleWrite("MORE OUTPUT" & @CRLF)

Output:

--> Press Ctrl+Alt+Break to Restart or Ctrl+Break to Stop
String: `@ +>11:36:54 AutoIt3.exe ended.rc:0
+>11:36:54 AutoIt3Wrapper Finished.
>Exit code: 0    Time: 0.2671

The output completely dies after ConsoleWrite($Test)... :blink:

Yeah, the lack of displaying pure binary is easy to fix and doesn't effect anything, really, because a MsgBox() confirms the binary is fine. I just found it lightly confusing. At first, I thought some variables were stubbornly not converting to binary and messed with it for a while trying to force binary conversion a few different ways, before I found that ConsoleWrite was messing with me... :huh2:



Whoa... I know I'm starting to get off topic, but I just found a bunch of neat console tricks that I never knew!

ConsoleWrite('! = Red' & @CRLF) ; ! = red text color
ConsoleWrite('> = Blue' & @CRLF) ; > = blue text color
ConsoleWrite('- = Orange' & @CRLF) ; - = orange text color
ConsoleWrite('+ = Green' & @CRLF) ; + = green text color
ConsoleWrite('(5) : = Red (jump to line 5 when double-clicked)' & @CRLF) ; '(5) :' red text color and double click jumps to (line number)
ConsoleWrite('Start with String or Integer then ' & @TAB & '6' & ' = Pink (jump to line 6 when double-clicked)' & @CRLF)
; pink text color, any sign and then @TAB & 'line number'

; Example 1
ConsoleWrite('(' & @ScriptLineNumber & ') : = Red (jump to line ' & @ScriptLineNumber & ' when double-clicked)' & @CRLF)

; Clear console output pane of SciTE after 5000 ms
Sleep(5000)
ControlSend("[CLASS:SciTEWindow]", "", "Scintilla2", "+{F5}")

 

Edited by BinaryBrother
  • Like 1

Share this post


Link to post
Share on other sites
jchd

The first ConsoleWrite in your first binary example has a leading binary 0, which the console interprets as an end of string. That's why all subsequent ConsoleWrite don't show up.


This wonderful site allows debugging and testing regular expressions (many flavors available). An absolute must have in your bookmarks.
Another excellent RegExp tutorial. Don't forget downloading your copy of up-to-date pcretest.exe and pcregrep.exe here
RegExp tutorial: enough to get started
PCRE v8.33 regexp documentation latest available release and currently implemented in AutoIt beta.

SQLitespeed is another feature-rich premier SQLite manager (includes import/export). Well worth a try.
SQLite Expert (freeware Personal Edition or payware Pro version) is a very useful SQLite database manager.
An excellent eBook covering almost every aspect of SQLite3: a must-read for anyone doing serious work.
SQL tutorial (covers "generic" SQL, but most of it applies to SQLite as well)
A work-in-progress SQLite3 tutorial. Don't miss other LxyzTHW pages!
SQLite official website with full documentation (may be newer than the SQLite library that comes standard with AutoIt)

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

  • Similar Content

    • boomingranny
      By boomingranny
      Use this UDF to add a console gui to your script (with log file):
      It uses the Hidden Autoit window (that you probably didn't even know existed)
      Closing Console window will terminate script.
      example of console:

      #include-once #include <GuiEdit.au3> EnableConsoleGui("example.log") ;example: ;------------------------ ConsoleWrite ("Hello World") For $i = 1 To 10 ConsoleWrite (".") Sleep(200) Next ConsoleWrite ("done") ConsoleWrite(@CRLF) ConsoleWrite ("close me to exit"&@CRLF) While 1 Sleep(1000) WEnd ;------------------------ ;end of example code Func EnableConsoleGui($Logfile="") ;EnableConsoleGUI ;by Daniel Barnes 20/04/2018 ;Uses AutoIt's Hidden window as a console (output only) Global $pidChild ;if we don't have a parent (as the parent window would have our script name) If Not WinExists(StringTrimRight(@ScriptName,4)) Then Opt("TrayIconHide",1) ;get Autoit's hidden window handle local $hWnd = WinGetHandle(AutoItWinGetTitle()) ;move the autoit hidden window to the middle of the screen WinMove($hWnd, "", (@DesktopWidth / 2) - 250, (@DesktopHeight / 2) - 250, 500, 500) ;get the Handle of the edit box in Autoit's hidden window $hEditBox = ControlGetHandle($hWnd,"","[CLASS:Edit; INSTANCE:1]") ;show it WinSetState($hWnd, "", @SW_SHOW) ;set its title = our script name WinSetTitle($hWnd,"",StringTrimRight(@ScriptName,4)) ;Spawn a child "copy" of the script, enabling reading of its console... If @Compiled Then ;2 = $STDOUT_CHILD. This avoids requiring the AutoItConstants.au3 in this sample code $pidChild= Run( FileGetShortName(@ScriptFullPath),@ScriptDir,"",2) Else ;2 = $STDOUT_CHILD. This avoids requiring the AutoItConstants.au3 in this sample code $pidChild= Run( FileGetShortName(@AutoItExe) & " " & FileGetShortName(@ScriptFullPath),@ScriptDir,"",2) EndIf OnAutoItExitRegister("EnableConsoleGui_CloseChildPID") ;read the console, while the child window exists (and the console window is visible) While ProcessExists($pidChild) $ConsoleRead = StdoutRead($pidChild) If $ConsoleRead then $text = StringLeft(ControlGetText($hWnd,"",$hEditBox),65535) If $Logfile Then FileWrite($Logfile,$ConsoleRead) $text &= $ConsoleRead ControlSetText($hWnd,"",$hEditBox,$text) ConsoleWrite($ConsoleRead) ;scroll to bottom of console edit window _GUICtrlEdit_SetSel($hEditBox, 65535, 65535) endif Sleep(250) WEnd exit endif EndFunc Func EnableConsoleGui_CloseChildPID() ;if this func isn't used ;when you close the console gui ;the child "clone" of your script will keep running ProcessClose($pidChild) EndFunc
    • kartune
      By kartune
      Hello, I am getting this error message when running my script:
      Case $aButiD[0] To $aButiD[$iTotButtons - 1]
      Case ^ ERROR
      Error:  Array variable has incorrect number of subscripts or subscript dimension range exceeded.
       
      The script's purpose is to read my ini file and create buttons for the sections and section contents.
      The first part of the script creates buttons for the sections of the ini, once you click on the section button it should open another set of buttons of all the contents under the section
      In this case, the section in the .ini file is called "TPA"
      on the Func flavorco()
      It opens the contents of "TPA" into buttons.
      Right now, the section it is reading is determined by $sSection.
      It is only when I try to change $sSection = "TPA"
      to
      $sSection = $flavorco
      that the error starts to appear
       
      Here is the script
      #include <MsgBoxConstants.au3> #include <WinAPIFiles.au3> #include <Array.au3> #include <GUIConstantsEx.au3> #include <WindowsConstants.au3> #include <ButtonConstants.au3> $optbar = IniReadSectionNames("test.ini") If Not IsArray($optbar) Then Exit Local $Button[UBound($optbar) - 1] $mGUI = GUICreate('Restock Flavor Ingredients', 10 + (130 * UBound($optbar)), 100) For $x = 1 To UBound($optbar) - 1 $var = IniReadSection("test.ini", $optbar[$x]) If @error Then ContinueLoop $X_Coord = 10 + (($x - 1) * 100) $Button[$x - 1] = GUICtrlCreateButton($optbar[$x], $X_Coord, 30, 70, 30) Next GUISetState() While 1 $mMsg = GUIGetMsg() If $mMsg = $GUI_EVENT_CLOSE Then GUIDelete($mGUI) ExitLoop EndIf For $i = 0 To UBound($Button) - 1 If $mMsg = $Button[$i] Then MsgBox(0, '$Msg = ' & $mMsg, GuiCtrlRead($Button[$i]) & ' Pressed', 2) Global $flavorco = $Button ; sets the flavor company's variable Call('flavorco') EndIf Next WEnd Func flavorco() ;opened flavor company's flavors MsgBox(0, '$Msg = ' & $mMsg, GuiCtrlRead($Button[$i]) & $flavorco, 0) Local $sFilePath = @ScriptDir & "\Test.ini" Local $sSection = $Button Local $aArray = IniReadSection($sFilePath, $sSection) _ArrayDelete($aArray, 0) ;_ArrayDisplay($aArray) Local $iIndex Local $iTotButtons = UBound($aArray) Local $iNumPerRow = 5 Local $iButWidth = 100 Local $iButDepth = 30 Local $aButiD[$iTotButtons] Local $hGUI = GUICreate('Ingredients Stock "' & $sFilePath & '"', 10 + ($iButWidth + 10) * $iNumPerRow, _ 10 + Ceiling($iTotButtons / $iNumPerRow) * ($iButDepth + 10), -1, $WS_EX_TOPMOST) For $i = 0 To $iTotButtons - 1 ; $x = $iXBorder + (($iRectWidth + $iSpacing) * Mod($i, $iNumCols)) $x = 10 + (($iButWidth + 10) * Mod($i, $iNumPerRow)) ; $y = $iYBorder + (($iRectDepth + $iSpacing) * Int($i / $iNumCols)) $y = 10 + (($iButDepth + 10) * Int($i / $iNumPerRow)) $aButiD[$i] = GUICtrlCreateButton($aArray[$i][0], $x, $y, $iButWidth, $iButDepth) ;, $BS_NOTIFY) Next GUISetState(@SW_SHOW) While 1 $msg = GUIGetMsg() Switch $msg Case $GUI_EVENT_CLOSE GUIDelete($hGUI) ExitLoop Case $aButiD[0] To $aButiD[$iTotButtons - 1] ;clicking on a flavor name $iIndex = ($msg - $aButiD[0]) $RSINGRflavor = $aArray[$iIndex][0] ;flavor name $RSINGRml = $aArray[$iIndex][1] ; ml $RSINGRgal = $aArray[$iIndex][1]*0.000264172 ;converts ml to gal Call('openflavor') EndSwitch WEnd EndFunc Func openflavor() #Region ### START Koda GUI section ### Form=F:\Karl\AutoIt\FJ-Stock JP\GUI Forms\RSINGRSUBFORM.kxf ;opens flavor to view stock and restock submit $RSINGRSUBFORM = GUICreate($sSection & " " & $RSINGRflavor, 242, 213, 530, 269) $RSINGRFlavorTitle = GUICtrlCreateLabel($sSection & " " & $RSINGRflavor, 32, 8, 200, 28) GUICtrlSetFont(-1, 16, 800, 0, "MS Sans Serif") $RSINGRstockcaption = GUICtrlCreateLabel("Current Stock in ml:", 16, 48, 96, 17) $RSINGRstockml = GUICtrlCreateLabel($RSINGRml, 120, 48, 114, 25) GUICtrlSetFont(-1, 8, 800, 0, "MS Sans Serif") $RSINGRInput = GUICtrlCreateInput("ml", 40, 112, 153, 21) $RSINGRSUBMIT = GUICtrlCreateButton("SUBMIT", 16, 152, 81, 33) $RSINGRCLOSE = GUICtrlCreateButton("CLOSE", 145, 151, 81, 33) $RSINGRgalcaption = GUICtrlCreateLabel("Current Stock in gal:", 16, 80, 97, 17) $RSINGRstockgal = GUICtrlCreateLabel($RSINGRGAL, 120, 80, 114, 25) GUICtrlSetFont(-1, 8, 800, 0, "MS Sans Serif") GUISetState(@SW_SHOW) #EndRegion ### END Koda GUI section ### ; $msg = "" While 1 $nMsg = GUIGetMsg() Switch $nMsg Case $GUI_EVENT_CLOSE GUIDelete($RSINGRSUBFORM) ExitLoop Case $RSINGRCLOSE GUIDelete($RSINGRSUBFORM) ExitLoop EndSwitch WEnd EndFunc  
      Any help is much appreciated!  Thanks.
      My guess is that $Button isn't an actual string??  Whenever I use msgbox it shows up the string exactly, no numbers attached.  So i'm not sure whats going on here.
    • FMS
      By FMS
      Hello,
      I'm trying to read a binary file to an array but couln't get it to work.
      Also I coul not find any help in the forum around this subject whish was helpfull.
      Is there any way it could be done?
      I tried a lot of ways but maybe somebody know's the right way?
      #AutoIt3Wrapper_Au3Check_Parameters=-d -w 1 -w 2 -w 3 -w 4 -w 5 -w 6 -w 7 #include <File.au3> #include <Array.au3> #include <AutoItConstants.au3> Local $in=FileOpen("TEST_labels.idx1-ubyte",16) ; 16+0=Read binary Local $data = FileRead($in) Local $FileArray = BinaryToString($data,4) ;~ $FileArray = StringSplit($BinarydData, @CRLF, 1+2) ;~ Local $FileArray = StringRegExp($BinarydData, "[^\r\n]+", 3) FileClose($in) _ArrayDisplay($FileArray,"$FileArray","",32) MsgBox($MB_SYSTEMMODAL, "", "$FileArray = " & $FileArray )  
      TEST_labels.idx1-ubyte
    • XinYoung
      By XinYoung
      Hello again,
      I'm trying to use the FileMove function to rename a bunch of text files.
      Some of the files have "_1" at the end of their name, for example, "File123_1.txt". I want to remove the "_1" so it would become "File123.txt".
      What I currently have...
              FileMove($sSource & "\*_1.txt", $sDestination & "\*.txt")
      But since I'm using a wildcard, it doesn't appear to be working. I think it's just replacing .txt with .txt. Am I going about this the wrong way? How can I use wildcards and still accomplish this?
      Any help is greatly appreciated ^__^
    • ur
      By ur
      I have date in the string format as "DD-MM-YYYY".
       
      I need to get yesterday's date from it.
      I tried converting this from _DateTimeFormat but not working.
      Is there any direct UDF available to get this.?
×

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.