Jump to content
Sign in to follow this  

Computing Padding Algorithm

Recommended Posts


For some obvious reason,

Sucessfully to translate an #computing padding algorithm,

and outputting same value with example of an explanation

Lets take a breath, wiki say:

The following formulas provide the number of padding bytes required to align the start of a data structure (where mod is the modulo operator):

# pseudo-code, see actual code below
padding = (align - (offset mod align)) mod align
new offset = offset + padding = offset + (align - (offset mod align)) mod align

For example, the padding to add to offset 0x59d for a structure aligned to every 4 bytes is 3. The structure will then start at 0x5a0, which is a multiple of 4. Note that when offset already is a multiple of align, the second modulo in (align - (offset mod align)) mod align is required to get a padding of 0.

Then I write AutoIt3 script.

ConsoleWrite(@CR & '+ Computing padding' & @CR)
Local $align, $offset, $padding, $new_offset

$align = 4
$offset = 0x59d

$padding = Mod($align - Mod($offset, $align), $align)
$new_offset = $offset + $padding + Mod($offset + ($align - Mod($offset, $align)), $align)

ConsoleWrite('padding: ' & $padding & '  new offset: 0x' & StringLower(Hex($new_offset, 4)) & @CR)

And the output is match with example in explanation.

+ Computing padding
padding: 3  new offset: 0x05a0

The question #01 are is that are correct translation? changing second line on second (=) (see below) with plus sign (+) in AutoIt3 (see above) ?

new offset = offset + padding = offset + (align - (offset mod align)) mod align


Again lets take a breath, wiki say:

If the alignment is a power of two, the modulo operation can be reduced to a bitwise boolean AND operation. The following formulas provide the new offset (where & is a bitwise AND and ~ a bitwise NOT):

padding = align - (offset & (align - 1)) = (-offset) & (align - 1)
new offset = (offset + align - 1) & ~(align - 1)

Then I write AutoIt3 script.

ConsoleWrite(@CR & '+ align 2 - Power of Two' & @CR)
Local $align, $offset, $padding, $new_offset

$align = 2
$offset = 0x59d

$padding = $align - (BitAND($offset, ($align - 1))) + BitAND((-$offset), ($align - 1))
$new_offset = BitAND(($offset + $align - 1), BitNOT($align - 1))

ConsoleWrite('padding: ' & $padding & '  new offset: 0x' & StringLower(Hex($new_offset, 4)) & @CR)

And the output is.

+ align 2 - Power of Two
padding: 2  new offset: 0x059e

The question #02. First line and second (=) I replace with plus (+) sign, again is that correct?

The question #03.

What is meaning from the word of 'The Power of Two'?

Are 2 is The Power of Two?

Are 4, 8, 16 is The Power of Two?

Which are the number are is The Power of Two and which is not?

Can someone give me an confirmation if translation that pseudo-code to AutoIt3 are correct.?

Can someone give me an explanation what is so called 'The Power of Two'.?

Please answer even if you think this are childish question, because I'm not from Brittain nor from American.

Edited by prazetto

# Button. Progressbar - Graphical AutoIt3 Control (UDF) # GTK on AutoIt3 - GTK+ Framework | Widgets

Share this post

Link to post
Share on other sites

You could be interessed in browsing this old thread, at least the posts about alignment and padding, roughly >starting here and on the following page.

The kth power of number N is N multiplied k times by itself, which we write Nk. By convention and because it's true, N0 = 1.

Then N1 = N, N2 = N * N, N3 = N * N * N and so on.

Successive powers of 2 are: 1, 2, 4, 8, 16, 32, 64, ...

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


Thanks for the answer about the power of n and 2. :thumbsup:

The link you pointed out are very helpfull for me.

Even the title of post are 'Latest Beta', but yes this are what I seek. :tv_horror:

Now I can continue my project. :sorcerer:

New update:

After reading those page back to 21, page 22 (pointed one) and next page 23.

At least it seem for me are temporary understand.

After try to understand then I try to translate and test.

The output size are match with DllStruct... family. Yes. :graduated:


; assume member size
Local $size[] = [2, 2, 4, 8, 1, 2]

; assume align 8, start at offset 0
Local $nAlign = 8, _ ; value are align option : 1, 2, 4, 8, 16
      $iOffset = 0, _
      $nTemp = 0, _
      $nLargestSize = 8 ; there max(size[]) = 8

For $loop = 0 To UBound($size)-1
   $iDataTypeSize = $size[$loop]

   ; Does this offset need padding first for correct alignment?
   If $iDataTypeSize < $nAlign Then
      $nTemp = Mod($iOffset, $iDataTypeSize)
      If $nTemp Then $nTemp = $iDataTypeSize - $nTemp
      $nTemp = Mod($iOffset, $nAlign)
      If $nTemp Then $nTemp = $nAlign - $nTemp
      $iOffset += $nTemp ; Update offset with padding

   ConsoleWrite('offset: #' & $loop & '  @  0x' & Ptr($iOffset) & '  size: ' & $size[$loop] & @CR)
   $iOffset += $iDataTypeSize

ConsoleWrite('offset: fn  @  0x' & Ptr($iOffset) & '  @pad :' & $iOffset & @CR)

   If ($nLargestSize < $nAlign) Then
      $nTemp = Mod($iOffset, $nLargestSize)
      If ($nTemp) Then $nTemp = $nLargestSize - $nTemp
      $nTemp = Mod($iOffset, $nAlign)
        If ($nTemp) Then $nTemp = $nAlign - $nTemp
    $iOffset = $iOffset + $nTemp;              // Update offset with padding

ConsoleWrite('offset: fn  @  0x' & Ptr($iOffset) & '  fin. :' & $iOffset & @CR & @CR)

ConsoleWrite('Compare with Native function' & @CR)
Local $mystruct = DllStructCreate('align ' & $nAlign & '; word; word; dword; int64; byte; word;')
ConsoleWrite('DllStruct* Family : ' & DllStructGetSize($mystruct) & @CR)

For $loop = 1 To 6
   ConsoleWrite('offset: #' & $loop-1 & '  @  ' & DllStructGetPtr($mystruct, $loop) - DllStructGetPtr($mystruct, 1) & @CR )

; jon:
;~ Individual member padding:
;~    // Does this offset need padding first for correct alignment?
;~    if (iDataTypeSize < nAlign)
;~    {
;~       nTemp = iOffset % iDataTypeSize;
;~       if(nTemp)
;~       nTemp = iDataTypeSize - nTemp;
;~    }
;~    else
;~    {
;~       nTemp = iOffset % nAlign;
;~       if(nTemp)
;~           nTemp = nAlign - nTemp;
;~    }
;~    iOffset += nTemp;                   // Update offset with padding

;~ End of structure padding:
;~    // Ensure the end of the structure is padded based on the size of the largest member
;~    if (nLargestSize < nAlign)
;~    {
;~       nTemp = iOffset % nLargestSize;
;~       if(nTemp)
;~           nTemp = nLargestSize - nTemp;
;~    }
;~    else
;~    {
;~       nTemp = iOffset % nAlign;
;~       if(nTemp)
;~           nTemp = nAlign - nTemp;
;~    }
;~    iOffset = iOffset + nTemp;              // Update offset with padding

; jchd:
;~ Individual member:
;~    // Does this offset need padding first for correct alignment of next member whose size is iDataTypeSize?
;~    nTemp = min(iDataTypeSize, nAlign);
;~    iOffset += (nTemp - (iOffset % nTemp)) % nTemp;                 // Update offset with padding

;~ Struct tail:
;~    // Ensure the end of the structure is padded based on the size of the smallest of (largest member or pack size)
;~    nTemp = min(nLargestSize, nAlign);
;~    iOffsetIn = iOffset + (nTemp - (iOffset % nTemp)) % nTemp;      // Update offset with padding


offset: #0  @  0x0x00000000  size: 2
offset: #1  @  0x0x00000002  size: 2
offset: #2  @  0x0x00000004  size: 4
offset: #3  @  0x0x00000008  size: 8
offset: #4  @  0x0x00000010  size: 1
offset: #5  @  0x0x00000012  size: 2
offset: fn  @  0x0x00000014  @pad :20
offset: fn  @  0x0x00000018  fin. :24

Compare with Native function
DllStruct* Family : 24
offset: #0  @  0x00000000
offset: #1  @  0x00000002
offset: #2  @  0x00000004
offset: #3  @  0x00000008
offset: #4  @  0x00000010
offset: #5  @  0x00000012

See the twenty four number!

Try change $nAlign, in my test. All align option 1, 2, 4, 8, 16 are match with native DllStruct... family.

Edited by prazetto

# Button. Progressbar - Graphical AutoIt3 Control (UDF) # GTK on AutoIt3 - GTK+ Framework | Widgets

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
Sign in to follow this  

  • Similar Content

    • argumentum
      By argumentum
      AutoIt Machine Code Algorithm Collection
      By Ward, November 11, 2010 in AutoIt Example Scripts 
      Posted November 11, 2010 (edited) I have already published a lot of AutoIt UDF about algorithm, but all of them only support 32 bits or so called X86 system. Recently I got a computer with Windows 7 64 bits, so I finally added X64 support to most of my old projects. Besides, I also added some new. For example, some compression algorithm and SHA3 Candidates.
      Following are the algorithms list:
      Checksum   CRC16   CRC32   ADLER32 Compression   FastLZ   LZF   LZMA   LZMAT   MiniLZO   QuickLZ Encode   Base64   ARC4   XXTEA   DES   AES Hash   Checksums (CRC16/CRC32/ADLER32)   MD2   MD4   MD5   SHA1   SHA2 (SHA224/256/384/512)   SHA3 Candidates     BLAKE     BMW (Blue Midnight Wish)     CUBEHASH     ECHO     SHABAL     SKEIN Some points to mention:
      All of the subroutines have one or more examples to demonstrate the usage. Since the function and usage of subroutine are easy to understand. A complete subroutines and parameters list are unavailability now. Sorry for my lazy. All of the subroutines here invoked by Lazycat's method (through CallWindowProc API). My MemoryDLL UDF is not necessary this time. Although MemoryFuncCall (part of MemoryDLL) is still good, but inevitably, it is slower than CallWindowProc. Some subroutines have the same name with my old machine code version UDF. But for some reason, I rearrange the position of the parameters. Please not mix up. If you notice, yes, checksums are duplicated. But they receive different parameters. One is the old style, and another use the same interface as other hashes. Choose what you like, but don't use them in the same time. Some algorithm already supported by the standard UDF "Encryption.au3". But I still provide them, because some system lack of the full support of Windows Crypt Library. If you are looking for only one hash algorithm, for example, used in encryption, I suggested "SHABAL_TINY.au3". Although it is a bit slower then SHABAL, but it is smaller, and it supports different size of output (from 32 to 512 bits).
    • ergo
      By ergo
      CronToTime.au3 UDF converts a Unix Cron expression into a DateTime string.
      On Unix systems a Cron expression made of five fields separated by blanks/tabs followed by a shell command to execute.

      e.g. 15-30 2,3,4,5 29 1-12 0-6 reboot
      +------------- minute (0 - 59)
      ¦ +------------- hour (0 - 23)
      ¦ ¦ +------------- day of month (1 - 31)
      ¦ ¦ ¦ +------------- month (1 - 12)
      ¦ ¦ ¦ ¦ +------------- day of week (0 - 6) (Sunday to Saturday, 7 is also Sunday)
      ¦ ¦ ¦ ¦ ¦ +------------- some shell command
      ¦ ¦ ¦ ¦ ¦ ¦
      ¦ ¦ ¦ ¦ ¦ ¦
      * * * * * reboot
      (In this UDF the 6th field has no meaning and no influence on the result).
      For more information see https://en.wikipedia.org/wiki/Cron

      Finds the next event of the specified Cron expression, starting from current UTC/GMT.
      _pce_findNextTimeUTC($sCronExp [, $bForwardSearch = True [, $minutesOffset = 0]]])
      Finds the next event of the specified Cron expression. If $sDateTime is not set, local time will be used.
      _pce_findNextTime($sCronExp [, $bForwardSearch = True [, $sDateTime = "" [, $minutesOffset = 0]]])
      Convert names in usable Cron expression values. e.g. "15-30 2,3,4,5 29 July-December Mo-Su" to "15-30 2,3,4,5 29 7-12 1-7"
      _pce_convertNames( $sCronExp )
      See the include for details.
    • MrCheese
      By MrCheese
      hi all,
      Dumb question, but say I have a loop:
      dim $i Do     sleep(1000)          if $i = ; how do i do a function that enters this IF statement every 10 loops?         ; do stuff every 10     EndIf      Until $i = 100  
      - what commands in the if statement do I need to use to make it pass, and on every 10th loop, it enters the if statement. ?
    • RTFC
      By RTFC
      CodeCrypter enables you to encrypt scripts without placing the key inside the script.
      This is because this key is extracted from the user environment at runtime by, for example:
      password user query any macro (e.g., @username) any AutoIt function call any UDF call some permanent environment variable on a specific machine (and not created by your script) a server response a device response anything else you can think of, as long as it's not stored in the script any combination of the above You need several scripts to get this to work, and they are scattered over several threads, so here's a single bundle that contains them all (including a patched version of Ward's AES.au3; with many thanks to Ward for allowing me to include this script here):
      Latest version: 2.3, (18 Jan 2018): CodeScannerCrypter.bundle.v2.3.7z
      Note: if you experience issues under Win8/8.1 (as some users have reported), please upgrade to Win10 (or use Win7) if you can; as far as I can tell, the scripts in the bundle all work under Win7 & Win10 (and XP). Moreover, I have no access to a Win8 box, so these issues will not be fixed, at least not by yours truly.
      How the bits and pieces fit together:
      CodeCrypter is a front-end for the MCF UDF library (you need version 1.3 or later). Its thread is here:
      '?do=embed' frameborder='0' data-embedContent>>
      The MCF package (also contained in the CodeScannerCrypter bundle) contains MCF.au3 (the library itself) plus a little include file called MCFinclude.au3. The latter you have to include in any script you wish to encrypt. Any code preceding it will not be encrypted, any code following it will be encrypted. You define the dynamic key inside MCFinclude.au3, in the UDF: _MCFCC_Init().
      From the same post you can download an MCF Tutorial which I heartily recommend, because encrypting a script requires a number of steps in the right order, namely:
      In MCFinclude.au3, define and/or choose your dynamic key(s) (skip this step = use default setting) include MCFinclude.au3 in your target script Run CodeScanner (version 2.3+) on your target script, with setting WriteMetaCode=True (see '?do=embed' frameborder='0' data-embedContent>>), then close CodeScanner. Start CodeCrypter press the Source button to load your target file enable Write MCF0 (tick the first option in Main Settings) Enable "Encrypt" (last option in the Main Settings) Go to the Tab Encrypt and set up the encryption the way you want (skip this = use default settings) Return to Main Tab and press "Run" if all goes well, a new script called MCF0test.au3 is created in the same directory as your target. It has no includes and no redundant parts. Please check that it works as normal. (see Remarks if not) It all sounds far more complicated than it is, really.
      Not convinced? Check out this updated and extended Q & A pdf (FAQ, also included in the bundle) to help you get started:
      For additional explanations/examples in response to specific questions by forum members (how it works, what it can/cannot do), see elsewhere in this thread, notably:
      Simple analogy of how it works: post #53, second part General Explanation and HowTo: post #9, 51, 75, 185/187, 196, 207, 270, 280 (this gets a bit repetitive) BackTranslation: post #179 Obfuscation: post #36 (general), 49 (selective obfuscation) Specific features and fixes: post #3 (security), 84 (redefining the expected runtime response), 169 (Curl Enum fix), 185/187 (using license keys), 194 (replacing Ward's AES UDF with different encryption/decryption calls), 251 (AV detection issue), 262 (extract key contents to USB on different target machine prior to encryption) Limitations: post #26 (@error/@extended), 149 (FileInstall), 191 (AES.au3 on x64) Not recommended: post #46/249 (static encryption), 102 (programme logic error), 237 (parsing password via cmdline)  
      Technical notes:
      BackTranslation is a test to check that the MetaCode translation worked. Skip it at your peril. It also turns your multi-include composite script into a single portable file without redundant parts (you can opt to leave the redundant parts in, if you want).
      CodeCrypter can also obfuscate (vars and UDF names) and replace strings, variable names and UDF names with anything else you provide, for  example, for language translation). After CodeScanner separates your target's structure from its contents, CodeCrypter (actually MCF, under the hood) can change any part, and then generate a new script from whichever pieces you define. See the MCF Tutorial for more explanation and examples.
      Encryption currently relies on Ward excellent AES UDF, but you can replace this with any other algorithm you like; just edit MCFinclude.au3 UDF _MCFCC(), and MCF.au3 UDF _EncryptEntry(), see post #194 in this thread.
      AES.au3, by Ward is now also included in bundle (with thanks to Ward), see '?do=embed' frameborder='0' data-embedContent>>
      Going to lie down now...
    • RTFC
      By RTFC
      MetaCode offers a way to:
      separate a script's structure from its content remove all redundant definitions (globals and UDFs) change any content (and some structure) combine (new) structure and (new) content into a new script The most useful applications implemented so far are:
      Fast language translation (not just text strings, also variable names and UDF names) Obfuscation (vars and/or UDFs) Script Encryption (conditionals, calls, and macros) Encryption is powerful because the key is not stored anywhere; you can define it to be a user password, macro, environment spec/variable, server response, something you define yourself, or a combination thereof; anything goes, as long as it's not a fixed string or fixed value. More info in the CodeCrypter thread: ?do=embed' frameborder='0' data-embedContent>'?do=embed' frameborder='0' data-embedContent>>
      ?do=embed' frameborder='0' data-embedContent>
      But MetaCode has more potential than that; it allows you to tinker with any type of content separately, then rebuild a new version. So for example, you can have a single script structure and numerous different language modules you just plug in to create a new version in a different language.
      A brief Tutorial is here:
      MetaCode Tutorial.pdf
      The MCF library itself can be found in the CodeScannerCrypter bundle:
      And a little example how to use it for translating your GUI into a different language:
       UI_Translator.7z (new version that should work with the new version of Google Translate, see post #13 below)
      MCF.au3 is just the library plus the MCFinclude.au3 file you need to include in any script you wish to encrypt.
      There is no GUI here. However, I did write a separate front-end for it called CodeCrypter, which you can find here:
      ?do=embed' frameborder='0' data-embedContent>'?do=embed' frameborder='0' data-embedContent>>
      ?do=embed' frameborder='0' data-embedContent>
      MCF uses output generated by my CodeScanner version 2.8+, which you can find here:
      '?do=embed' frameborder='0' data-embedContent>>
      CodeScanner also depends on MCF.au3 now, as it can now call a few of its functions.
      I should also mention Ward's excellent AES.au3 UDFs used for the encryption and decryption calls,  which is now included in the CodeScannerCrypter bundle (thanks to Ward for allowing to include it). You can find the original (unpatched) version here:
      '?do=embed' frameborder='0' data-embedContent>>
      Note: you can replace the encryption/decryption calls with whatever algorithm you like (hint: the native <Crypt.au3> library is too slow for most purposes, better stick to machine code routines)
      So just to be clear:
      CodeScanner (v2.8+) needs MCF (earlier versions won't work!) CodeCrypter needs MCF (plus anything that MCF needs) MCF itself needs MCFinclude (part of MCF zip) MCF also needs readCSdatadump (part of the CodeScanner package, you need the latest version packaged with CodeScanner v2.8; earlier versions won't work!) both MCF and MCFinclude currently rely on AES.au3 by Ward So you basically need to download the whole bundle for any of it to work.
      If you have any questions, please start by reading the MCF Tutorial and the CodeCrypter FAQ (you can download the latter separately from the CodeCrypter thread).
      Next, read the extensive Remarks sections in MCF.au3, MCFinclude.au3, and CodeCrypter.au3
      If still no joy, then please post. However, I'm not online that often, and logged in to the forum even less, so response may take a while).