Jump to content

ConvertFileSize UDF


Steveiwonder
 Share

Recommended Posts

Hey All,

Very small UDF i've thrown together. I'm using FILEGETSIZE alot in my current project and it returns the size in bytes... i needed to convert this to either GB MB or KB.

Thought i'd share it as i couldn't find anything else on the forum.

UDF:

;==================================================================================
; AutoIt Version:   3.3.4.0
; Language:         English
; Author:           Steveiwonder
; Requirements:     None
;==================================================================================
; Function:         ConvertSize
; Description:      Converts a given number(bytes) into GB/MB/KB/B
; Parameter(s):     $FileSizeInBytes - the size of file / folder in bytes


; Return Value(s):  Returns array
;                   [0] contains the converted file/folder size in GB/MB/KB/B rounded to two decimal places.
;                   [1] contains either GB/MB/KB/B
; Author(s):        Steveiwonder
;==================================================================================
Func _ConvertSize($FileSizeInBytes)
    
    Local $n[2] = [$FileSizeInBytes, ""]

        
    If $n[0] >= 1073741824 Then ; = or greater than 1GB
        $n[0] = $n[0]/(1024*1024*1024)
        $n[1]= "GB"
        
    ElseIf $n[0] >= 1048576 Then ; = or greater than 1MB
        $n[0] = $n[0]/(1024*1024)
        $n[1]= "MB"     
    
    ElseIf $n[0] >= 1024 Then ; = or greater than 1KB
        $n[0] = $n[0]/(1024)
        $n[1]= "KB"
        
    Else
        $n[0] = $n[0]
        $n[1]= "B"      
    EndIf
    
    $n[0] = Round($n[0], 2)
    
    Return $n
EndFunc

Example Script:

#include "func_ConvertFileSize.au3"
$fileSize = DirGetSize("C:\Windows")
$xSize = _ConvertSize($fileSize)

MsgBox(64, "Size Conversion", $fileSize & " bytes = " & $xSize[0] & " " & $xSize[1])

Do what you want with it, i'm sure it can be modified to make it better.

Steveiwonder

func_ConvertFileSize.au3

Edited by Steveiwonder

They call me MrRegExpMan

Link to comment
Share on other sites

Nice, but have been done before: http://www.autoitscript.com/forum/index.php?showtopic=63770&view=findpost&p=475855

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

Func _String_GetFormattedSize($iByteSize, $iRound=2, $sRetFormat=-1)
    Local $asBytes[9] = [8, 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] ;Last two unreachable ;)
    Local $iBytes_Val = 2 ^ 10
    
    If $iByteSize < $iBytes_Val Then Return $iByteSize & ' Bytes'
    
    Local $iRetFormat_IsString = IsString($sRetFormat)
    Local $iFor = 1, $iTo = 8, $iStep = 1
    
    If $iRetFormat_IsString Then
        If Not StringRegExp($sRetFormat, "\A(?i)(KB|MB|GB|TB|PB|EB|ZB|YB)\z") Then Return SetError(1, 0, $iByteSize)
    Else
        Local $iFor = 8, $iTo = 1, $iStep = -1
    EndIf
    
    For $i = $iFor To $iTo Step $iStep
        If ($iRetFormat_IsString And $sRetFormat = $asBytes[$i]) Or _
            (Not $iRetFormat_IsString And $iByteSize >= $iBytes_Val ^ $i) Then
                Return Round($iByteSize / $iBytes_Val ^ $i, $iRound) & ' ' & $asBytes[$i]
        EndIf
    Next
EndFunc

 

Spoiler

Using OS: Win 7 Professional, Using AutoIt Ver(s): 3.3.6.1 / 3.3.8.1

AutoIt_Rus_Community.png AutoIt Russian Community

My Work...

Spoiler

AutoIt_Icon_small.pngProjects: ATT - Application Translate Tool {new}| BlockIt - Block files & folders {new}| SIP - Selected Image Preview {new}| SISCABMAN - SciTE Abbreviations Manager {new}| AutoIt Path Switcher | AutoIt Menu for Opera! | YouTube Download Center! | Desktop Icons Restorator | Math Tasks | KeyBoard & Mouse Cleaner | CaptureIt - Capture Images Utility | CheckFileSize Program

AutoIt_Icon_small.pngUDFs: OnAutoItErrorRegister - Handle AutoIt critical errors {new}| AutoIt Syntax Highlight {new}| Opera Library! | Winamp Library | GetFolderToMenu | Custom_InputBox()! | _FileRun UDF | _CheckInput() UDF | _GUIInputSetOnlyNumbers() UDF | _FileGetValidName() UDF | _GUICtrlCreateRadioCBox UDF | _GuiCreateGrid() | _PathSplitByRegExp() | _GUICtrlListView_MoveItems - UDF | GUICtrlSetOnHover_UDF! | _ControlTab UDF! | _MouseSetOnEvent() UDF! | _ProcessListEx - UDF | GUICtrl_SetResizing - UDF! | Mod. for _IniString UDFs | _StringStripChars UDF | _ColorIsDarkShade UDF | _ColorConvertValue UDF | _GUICtrlTab_CoverBackground | CUI_App_UDF | _IncludeScripts UDF | _AutoIt3ExecuteCode | _DragList UDF | Mod. for _ListView_Progress | _ListView_SysLink | _GenerateRandomNumbers | _BlockInputEx | _IsPressedEx | OnAutoItExit Handler | _GUICtrlCreateTFLabel UDF | WinControlSetEvent UDF | Mod. for _DirGetSizeEx UDF
 
AutoIt_Icon_small.pngExamples: 
ScreenSaver Demo - Matrix included | Gui Drag Without pause the script | _WinAttach()! | Turn Off/On Monitor | ComboBox Handler Example | Mod. for "Thinking Box" | Cool "About" Box | TasksBar Imitation Demo

Like the Projects/UDFs/Examples? Please rate the topic (up-right corner of the post header: Rating AutoIt_Rating.gif)

* === My topics === *

==================================================
My_Userbar.gif
==================================================

 

 

 

AutoIt is simple, subtle, elegant. © AutoIt Team

Link to comment
Share on other sites

  • 5 years later...

Quick search, a small modification, and this is the end result:

MsgBox(0, '', _String_GetFormattedSizeEx(7098459644))

; #FUNCTION# ====================================================================================================================
; Name ..........: _String_GetFormattedSizeEx
; Description ...: Return ByteSize in human-readable format ("complex format" GB + MB + KB )
; Syntax ........: _String_GetFormattedSizeEx($iByteSize)
; Parameters ....: $iByteSize           - an integer value.
; Return values .: ByteSize in format like this:  7 GB 770 MB 089 KB
; Author ........: mLipok
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _String_GetFormattedSizeEx($iByteSize)
    Local $sKB = _String_GetFormattedSize(7098459644, 0, 'KB')
    Local $sMB = _String_GetFormattedSize(7098459644, 0, 'MB')
    Local $sGB = _String_GetFormattedSize(7098459644, 0, 'GB')
    Return $sGB & ' ' & StringRight($sMB, 6) & ' ' & StringRight($sKB, 6)
EndFunc   ;==>_String_GetFormattedSizeEx

; #FUNCTION# ====================================================================================================================
; Name ..........: _String_GetFormattedSize
; Description ...: Return ByteSize in human-readable format (one of avalaible size format)
; Syntax ........: _String_GetFormattedSize($iByteSize[, $iRound = 2[, $sRetFormat = -1]])
; Parameters ....: $iByteSize           - an integer value.
;                  $iRound              - [optional] an integer value. Default is 2.
;                  $sRetFormat          - [optional] a string value. Default is -1.
; Return values .: ByteSize in choosen format
; Author ........: MrCreatoR
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........: https://www.autoitscript.com/forum/topic/110713-convertfilesize-udf/#comment-777347
; Example .......: No
; ===============================================================================================================================
Func _String_GetFormattedSize($iByteSize, $iRound = 2, $sRetFormat = -1)
    Local $asBytes[9] = [8, 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'] ;Last two unreachable ;)
    Local $iBytes_Val = 2 ^ 10

    If $iByteSize < $iBytes_Val Then Return $iByteSize & ' Bytes'

    Local $iRetFormat_IsString = IsString($sRetFormat)
    Local $iFor = 1, $iTo = 8, $iStep = 1

    If $iRetFormat_IsString Then
        If Not StringRegExp($sRetFormat, "\A(?i)(KB|MB|GB|TB|PB|EB|ZB|YB)\z") Then Return SetError(1, 0, $iByteSize)
    Else
        Local $iFor = 8, $iTo = 1, $iStep = -1
    EndIf

    For $i = $iFor To $iTo Step $iStep
        If ($iRetFormat_IsString And $sRetFormat = $asBytes[$i]) Or _
                (Not $iRetFormat_IsString And $iByteSize >= $iBytes_Val ^ $i) Then
            Return Round($iByteSize / $iBytes_Val ^ $i, $iRound) & ' ' & $asBytes[$i]
        EndIf
    Next
EndFunc   ;==>_String_GetFormattedSize

 

Now ready to use in my script.
Thanks for sharing.


mLipok

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
Share on other sites

  • 3 years later...

there was a bug in my _String_GetFormattedSizeEx()

Here is fixed version:

; #FUNCTION# ====================================================================================================================
; Name ..........: _String_GetFormattedSizeEx
; Description ...: Return ByteSize in human-readable format ("complex format" GB + MB + KB )
; Syntax ........: _String_GetFormattedSizeEx($iByteSize)
; Parameters ....: $iByteSize           - an integer value.
; Return values .: ByteSize in format like this:  7 GB 770 MB 089 KB
; Author ........: mLipok
; Modified ......:
; Remarks .......:
; Related .......:
; Link ..........:
; Example .......: No
; ===============================================================================================================================
Func _String_GetFormattedSizeEx($iByteSize)
    Local Enum _
            $SIZE_B = 1, _
            $SIZE_KB = $SIZE_B * 1024, _
            $SIZE_MB = $SIZE_KB * 1024, _
            $SIZE_GB = $SIZE_MB * 1024

    Local $SIZE_GB_DIV = Int($iByteSize / $SIZE_GB)
    $iByteSize = $iByteSize - ($SIZE_GB * $SIZE_GB_DIV)

    Local $SIZE_MB_DIV = Int($iByteSize / $SIZE_MB)
    $iByteSize = $iByteSize - ($SIZE_MB * $SIZE_MB_DIV)

    Local $SIZE_KB_DIV = Int($iByteSize / $SIZE_KB)
    $iByteSize = $iByteSize - ($SIZE_KB * $SIZE_KB_DIV)

    Local $SIZE_B_DIV = Int($iByteSize / $SIZE_B)
    $iByteSize = $iByteSize - ($SIZE_B * $SIZE_B_DIV)

    Local $sResult = $SIZE_GB_DIV & ' GB ' & StringRight($SIZE_MB_DIV, 6) & ' MB ' & StringRight($SIZE_KB_DIV, 6) & ' KB'
    ConsoleWrite("! $iByteSize = " & $iByteSize & @CRLF)
    If $iByteSize <> 0 Then _
            Return SetError(1, 0, $sResult)
    ConsoleWrite("! " & $sResult & @CRLF)
    Return $sResult
EndFunc   ;==>_String_GetFormattedSizeEx

 

Signature beginning:
Please remember: "AutoIt"..... *  Wondering who uses AutoIt and what it can be used for ? * Forum Rules *
ADO.au3 UDF * POP3.au3 UDF * XML.au3 UDF * IE on Windows 11 * How to ask ChatGPT for AutoIt Codefor other useful stuff click the following button:

Spoiler

Any of my own code posted anywhere on the forum is available for use by others without any restriction of any kind. 

My contribution (my own projects): * Debenu Quick PDF Library - UDF * Debenu PDF Viewer SDK - UDF * Acrobat Reader - ActiveX Viewer * UDF for PDFCreator v1.x.x * XZip - UDF * AppCompatFlags UDF * CrowdinAPI UDF * _WinMergeCompare2Files() * _JavaExceptionAdd() * _IsBeta() * Writing DPI Awareness App - workaround * _AutoIt_RequiredVersion() * Chilkatsoft.au3 UDF * TeamViewer.au3 UDF * JavaManagement UDF * VIES over SOAP * WinSCP UDF * GHAPI UDF - modest begining - comunication with GitHub REST APIErrorLog.au3 UDF - A logging Library * Include Dependency Tree (Tool for analyzing script relations) * Show_Macro_Values.au3 *

 

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 UDF * ADO.au3 UDF SMTP Mailer UDF * Dual Monitor resolution detection * * 2GUI on Dual Monitor System * _SciLexer.au3 UDF * SciTE - Lexer for console pane

Useful links: * Forum Rules * Forum etiquette *  Forum Information and FAQs * How to post code on the forum * AutoIt Online Documentation * AutoIt Online Beta Documentation * SciTE4AutoIt3 getting started * Convert text blocks to AutoIt code * Games made in Autoit * Programming related sites * Polish AutoIt Tutorial * DllCall Code Generator * 

Wiki: Expand your knowledge - AutoIt Wiki * Collection of User Defined Functions * How to use HelpFile * Good coding practices in AutoIt * 

OpenOffice/LibreOffice/XLS Related: WriterDemo.au3 * XLS/MDB from scratch with ADOX

IE Related:  * How to use IE.au3  UDF with  AutoIt v3.3.14.x * Why isn't Autoit able to click a Javascript Dialog? * Clicking javascript button with no ID * IE document >> save as MHT file * IETab Switcher (by LarsJ ) * HTML Entities * _IEquerySelectorAll() (by uncommon) * IE in TaskSchedulerIE Embedded Control Versioning (use IE9+ and HTML5 in a GUI) * PDF Related:How to get reference to PDF object embeded in IE * IE on Windows 11

I encourage you to read: * Global Vars * Best Coding Practices * Please explain code used in Help file for several File functions * OOP-like approach in AutoIt * UDF-Spec Questions *  EXAMPLE: How To Catch ConsoleWrite() output to a file or to CMD *

I also encourage you to check awesome @trancexx code:  * Create COM objects from modules without any demand on user to register anything. * Another COM object registering stuffOnHungApp handlerAvoid "AutoIt Error" message box in unknown errors  * HTML editor

winhttp.au3 related : * https://www.autoitscript.com/forum/topic/206771-winhttpau3-download-problem-youre-speaking-plain-http-to-an-ssl-enabled-server-port/

"Homo sum; humani nil a me alienum puto" - Publius Terentius Afer
"Program are meant to be read by humans and only incidentally for computers and execute" - Donald Knuth, "The Art of Computer Programming"
:naughty:  :ranting:, be  :) and       \\//_.

Anticipating Errors :  "Any program that accepts data from a user must include code to validate that data before sending it to the data store. You cannot rely on the data store, ...., or even your programming language to notify you of problems. You must check every byte entered by your users, making sure that data is the correct type for its field and that required fields are not empty."

Signature last update: 2023-04-24

Link to comment
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
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...