TECHNOLOGIES
FORUMS
JOBS
BOOKS
EVENTS
INTERVIEWS
Live
MORE
LEARN
Training
CAREER
MEMBERS
VIDEOS
NEWS
BLOGS
Sign Up
Login
No unread comment.
View All Comments
No unread message.
View All Messages
No unread notification.
View All Notifications
Answers
Post
An Article
A Blog
A News
A Video
An EBook
An Interview Question
Ask Question
Forums
Monthly Leaders
Forum guidelines
Subrata
NA
7
718
Convert KB,KiB,MB,MiB,GB,GiB,TB,TiB to bytes and vice versa
Apr 13 2020 3:42 AM
Need to convert incoming input in units KB,KiB,MB,MiB,GB,GiB,TB,TiB to bytes to display as output.
Also, Need to convert incoming input in bytes to best suited units KB,KiB,MB,MiB,GB,GiB,TB,TiB and give as output.
Also, have to be sure of precision and convert to the best possible unit.
I tried the below. Is there any better way to code this?Could someone please help me?
Function 1:
public
static
string
ConvertFromBytes(
double
size)
{
string
postfix =
"Bytes"
;
double
result = size;
if
(size >= 1099511627776)
{
result = size / 1099511627776;
postfix =
"TiB"
;
}
else
if
(size >= 1000000000000)
{
result = size / 1000000000000;
postfix =
"TB"
;
}
else
if
(size >= 1073741824)
{
result = size / 1073741824;
postfix =
"GiB"
;
}
else
if
(size >= 1000000000)
{
result = size / 1000000000;
postfix =
"GB"
;
}
else
if
(size >= 1048576)
{
result = size / 1048576;
postfix =
"MiB"
;
}
else
if
(size >= 1000000)
{
result = size / 1000000;
postfix =
"MB"
;
}
else
if
(size >= 1024)
{
result = size / 1024;
postfix =
"KiB"
;
}
else
if
(size >= 1000)
{
result = size / 1000;
postfix =
"KB"
;
}
return
result.ToString(
"F1"
) +
" "
+ postfix;
//convert to float.
}
Function 2:
public
static
ulong
ConvertToBytes(
ulong
value,
string
unit)
{
ulong
size = 0;
switch
(unit)
{
case
"KB"
:
size = value * 1024;
break
;
case
"MB"
:
size = value * 1024 * 1024;
break
;
case
"GB"
:
size = value * 1024 * 1024 * 1024;
break
;
case
"TB"
:
size = value * 1024 * 1024 * 1024 * 1024;
break
;
case
"PB"
:
size = value * 1024 * 1024 * 1024 * 1024 * 1024;
break
;
default
:
size = value;
break
;
}
return
size;
}
Reply
Answers (
1
)
How to clear data after Browser back button click ?
gecko Browser not supporting adobe connect site