WoodGrain

Convert Dec to Binary - but Ones and Zeros

8 posts in this topic

#1 ·  Posted (edited)

Hi All,

Trying to convert a number to binary zeros and ones but I'm getting a result I don't understand and looks more like hex than binary.

Here's my basic code:

$myNum = 11
$myNumBin = Binary($myNum)
MsgBox(0, "Binary result", $myNumBin)

What I want is "1011", what I get is 0x0B000000.

Thanks!

Edited by WoodGrain
Wrong syntax

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Try this:

MsgBox(0, "", DecToBase(11, 2))

Func DecToBase($iInt, $iBase) ; for bases 2 to 9
    Local $iRem, $sRet = ''
    While $iInt > $iBase -1
        $iRem = Mod($iInt, $iBase)
        $sRet = $iRem & $sRet
        $iInt = Int(($iInt - $iRem) /$iBase)
    WEnd
    Return $iInt & $sRet
EndFunc ;==> DecToBase


To reverse the process you can use this:

MsgBox(0, "", BaseToDec('1011', 2))

Func BaseToDec($sInt, $iBase) ; bases 2 to 9 only
    Local $iRet = 0, $iLen = StringLen($sInt)
    For $i = 1 To $iLen
        $iRet += StringMid($sInt, $i, 1) * $iBase ^ ($iLen - $i)
    Next
    Return $iRet
EndFunc ;==> BaseToDec

 

Edited by czardas
1 person likes this

Share this post


Link to post
Share on other sites

That worked perfectly, thanks!

I note it does bases 2 - 9, would it be complex to allow up to base 16 so I can convert it to hex as well?

Share this post


Link to post
Share on other sites

#4 ·  Posted (edited)

It's not so complicated, but unless you need bases 11 to 15, you might as well use Hex() and Dec(). I don't have much time this morning. You could try this old code of mine:
 http://www.czardas.co.uk/repository/math10.au3

The code I posted in this thread can also be modified to convert larger numbers (up to Int64) by replacing the operators with operator64 functions (see my signature). Currently, these conversion functions only work for doubles ~ up to 15 decimal digits.

Edited by czardas

Share this post


Link to post
Share on other sites

#5 ·  Posted (edited)

No worries, thanks very much.

Actually, yeah, hex() works as expected

$myNum = 30
$myNumHex = Hex($myNum, 2)
MsgBox(0, "Hex result", $myNumHex)

Returns 1E

Edited by WoodGrain
Update after testing

Share this post


Link to post
Share on other sites
18 hours ago, czardas said:

$iInt = Int(($iInt - $iRem) /$iBase)

This line could be written like this with no change in output.

$iInt = Int($iInt / $iBase)

 

1 person likes this

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

#7 ·  Posted (edited)

@BrewManNH Well spotted! By all means change it.

Instead of that, if I implement Operator64 functions, Int() could be removed. It should not really be needed here neither, but because of rounding inaccuracies, I added it to be on the safe side. That's also why I decided on division by a real factor (subtracting the remainder first): I don't trust double precision to always return an accurate result.

It's a while since I wrote this and I'm trying to remember everything I was thinking at the time. I must have written it that way because of the aforementioned reasons.

Edited by czardas

Share this post


Link to post
Share on other sites

#8 ·  Posted (edited)

I have modified this method to be compatible with all numbers within the positive Int64 range. This example requires operator64.au3 (see link in my signature).

CODE MOVED HERE:

Edited by czardas

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

    • Dragonfighter
      By Dragonfighter
      I'm searching a way to do xor and shift and if possible also other operations. Thanks in advance for the replies.
    • rudi
      By rudi
      Hello.
      I'm too stupid to see my mistake:
      To investigate the internal "dictionary" of TIFF files I'd like to read in the files in binary mode and to check, if there are more than one pages "in" this TIFF.
      Notepad++, "View as Hex" is presenting the first bytes as "49 49 2a 20 08 20 20 20 12" for the TIF attached to this posting
      The "TIFF Header Format" is easy:
      Offset 00h, 2 Byte = Byte Order, "II"=intel, "MM"=motorola. (I = 0x49)
      --> II
      Offset 02h, 2 Byte = Version Nr.
      Offset 04h, 4 Byte = pointer to first IFD entry
      Description of TIFF header: https://www.awaresystems.be/imaging/tiff/faq.html#q3
       

      Howto read and analyse the binary content correctly? This is my messy, not operational code:
       
      $sampleTiff="H:\daten\tif\11\11\111111.TIF" $h=FileOpen($sampleTiff,16) $content=FileRead($h) ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $content = ' & $content & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console FileClose($h) $type=VarGetType($content) ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $type = ' & $type & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console $ToString=BinaryToString($content) ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $ToString = ' & $ToString & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console ConsoleWrite(@CRLF & @CRLF) $content=StringTrimLeft($content,2) ; cut off the leading "0x" ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $content = ' & $content & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console for $i = 1 to 8 step 8 $next=StringMid($content,$i,2) ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $next = ' & $next & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console $Chr=BinaryToString($next) ConsoleWrite('@@ Debug(' & @ScriptLineNumber & ') : $Chr = ' & $Chr & @CRLF & '>Error code: ' & @error & @CRLF) ;### Debug Console ConsoleWrite(@CRLF & "---" & @CRLF) Next Regards, Rudi.
      111111.TIF
    • ur
      By ur
      When I am trying to compile the autoit files with aut2exe.
      I am getting below error.
      There is no issue in code as the same code is getting compiled on different machine.
      I tried reinstalling the AUtoIT, but the issue replicates.

      Any suggestions?
    • FrancescoDiMuro
      By FrancescoDiMuro
      Good evening
      I was looking around the forum if I could find a function that allows to convert a string into a 2 dimensional array...
      The first column of the array is always the same, but the rows could change...
      I have a pattern like:

      Column A|Column B
      Static Text 1|Data 1
      Static Text 2|Data 2
      Static Text 3|Data 3
      Static Text 4|Data 4

      Where, Static Text (1...4) will be always the same, and I don't want to change them... But, Data 1...4 are dynamic fields... So, I could have the pattern above AND I coould have the pattern I'm going to show you right below

      Column A|Column B
      Static Text 1|Data 1
      Static Text 2|Data 2
      Static Text 3|Data 3
      Static Text 4|Data 4
      Static Text 1|Data 5
      Static Text 2|Data 6
      Static Text 3|Data 7
      Static Text 4|Data 8

      How can I do in this case?

      Thanks for everyone's help


       
    • wakillon
      By wakillon
      BinaryToAu3Kompressor v1.0.5.4
       

       
      It's now possible to see the best compression ratio using LZMA, LZNT and Base64 compressions with differents combinations.
      Nothing too complicate, you drag'n drop a file on the picture and script Test all compression types and return the ratios.
      ( Test duration depends of file size, slowest compression is LZNT, but all decompressions are fast  )
      Free to you after, to choose the compression(s) you want...
      Yes, LZMA needs a dll ( embedded & compressed in script ) but brings a powerfull compression. 
      It opens scite with your file compressed to an au3 script with or without decompression function as you want.
      Hold Left Shift key when clicking button for just copy script to clipboard.
      Use the 3 compressions at a time works but doesn't give a good ratio, that's why i don't display it.
      Usefull for little files you want include in your scripts !
      No externals files needed, they are already in script.
      Previous downloads : 1103
      Source and Executable
      BinaryToAu3Kompressor will be added to the next version of >SciTEHopper
      Thanks to Ward for his >Base64.au3 and LZMA.au3, and trancexx for his >LZNT functions and his >Base64Decode function.