Steveiwonder

ConvertFileSize UDF

5 posts in this topic

#1 ·  Posted (edited)

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

Share this post


Link to post
Share on other sites



#2 ·  Posted (edited)

Nice!! I've also been converting bytes to human-readable formats a lot... This UDF makes it much easier, neater and consistent. Thanks for your share.

Edited by dmob

Share this post


Link to post
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

Share this post


Link to post
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

1 person likes this

 

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

Share this post


Link to post
Share on other sites

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:   Wondering who uses AutoIT and what it can be used for ?
* GHAPI UDF - modest begining - comunication with GitHub REST API *
ADO.au3 UDF     POP3.au3 UDF     XML.au3 UDF    How to use IE.au3  UDF with  AutoIt v3.3.14.x  for 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 API *

My contribution to others projects or UDF based on  others projects: * _sql.au3 UDF  * POP3.au3 UDF *  RTF Printer - UDF * XML.au3 - BETA * ADO.au3 UDF SMTP Mailer UDF *

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 * Best coding practices * 

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) * 

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 *

"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: 2017-06-04

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