Unit Conversion Guide for Developers: Data, Time, and Numbers

datafmt.com Team
#development #programming #conversion #data #performance
5 min read

Every developer encounters unit conversions daily—whether calculating storage requirements, estimating API response times, or debugging timestamp issues. Understanding these conversions is crucial for writing efficient code, making accurate estimates, and avoiding subtle bugs.

This guide covers the essential conversions developers need: data storage units, time calculations, and number system conversions.

Data Storage Units

The Binary vs Decimal Debate

One of the most confusing aspects of data storage is the difference between decimal (SI) and binary (IEC) units.

Decimal (SI) Units:

  • Kilobyte (KB): 1,000 bytes
  • Megabyte (MB): 1,000,000 bytes
  • Gigabyte (GB): 1,000,000,000 bytes
  • Terabyte (TB): 1,000,000,000,000 bytes

Used by: Hard drive manufacturers, network speeds, file sizes in macOS

Binary (IEC) Units:

  • Kibibyte (KiB): 1,024 bytes
  • Mebibyte (MiB): 1,048,576 bytes
  • Gibibyte (GiB): 1,073,741,824 bytes
  • Tebibyte (TiB): 1,099,511,627,776 bytes

Used by: Operating systems (Windows/Linux), RAM specifications, actual storage

Why This Matters

// Marketing: 1TB hard drive
const marketingSize = 1_000_000_000_000; // bytes

// Actual capacity in OS
const osSize = Math.floor(marketingSize / (1024**4)); // 0.909 TiB

// That's a 91GB difference!
const difference = marketingSize - (0.909 * (1024**4));
// ≈ 100,000,000,000 bytes "missing"

Takeaway: Always clarify which unit system you’re using in documentation and code.

Common Data Storage Conversions

Bytes to Human-Readable Format:

function formatBytes(bytes, decimals = 2) {
  if (bytes === 0) return '0 Bytes';
  
  const k = 1024; // Use 1000 for decimal
  const sizes = ['Bytes', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
  const i = Math.floor(Math.log(bytes) / Math.log(k));
  
  return `${(bytes / Math.pow(k, i)).toFixed(decimals)} ${sizes[i]}`;
}

// Examples
formatBytes(1536); // "1.50 KiB"
formatBytes(1048576); // "1.00 MiB"
formatBytes(123456789); // "117.74 MiB"

Bits vs Bytes in Networking:

Network speeds use bits per second (bps), while file sizes use bytes:

// Convert Mbps to MB/s
const mbps = 100; // Internet speed
const megaBytesPerSecond = mbps / 8; // 12.5 MB/s

// Download time calculation
const fileSizeMB = 500; // 500 MB file
const downloadTimeSeconds = fileSizeMB / megaBytesPerSecond; // 40 seconds

Remember: 1 Byte = 8 bits, so divide Mbps by 8 to get MB/s.

Practical Database Examples

Estimating Database Size:

-- Calculate table size in PostgreSQL
SELECT 
  pg_size_pretty(pg_total_relation_size('users')) AS total_size,
  pg_size_pretty(pg_table_size('users')) AS table_size,
  pg_size_pretty(pg_indexes_size('users')) AS indexes_size;

Planning Storage Requirements:

// Estimate storage for user avatars
const avgAvatarSize = 500 * 1024; // 500 KiB
const totalUsers = 100_000;
const totalStorage = avgAvatarSize * totalUsers;

console.log(formatBytes(totalStorage)); 
// "47.68 GiB" - plan for ~50GB

Time Units and Calculations

Unix Timestamps

Unix time counts seconds since January 1, 1970 (UTC), the “Unix epoch.”

Timestamp Precision:

// Seconds (Unix timestamp)
const unixSeconds = Math.floor(Date.now() / 1000);
// 1700000000

// Milliseconds (JavaScript Date)
const jsTimestamp = Date.now();
// 1700000000000

// Microseconds (some databases)
const microseconds = jsTimestamp * 1000;
// 1700000000000000

// Nanoseconds (Go, Rust)
const nanoseconds = jsTimestamp * 1_000_000;
// 1700000000000000000

Common bug: Mixing timestamp precisions when integrating systems!

Duration Conversions

// Time unit constants
const SECOND = 1000; // ms
const MINUTE = 60 * SECOND;
const HOUR = 60 * MINUTE;
const DAY = 24 * HOUR;
const WEEK = 7 * DAY;

// Human-readable duration
function formatDuration(ms) {
  const days = Math.floor(ms / DAY);
  const hours = Math.floor((ms % DAY) / HOUR);
  const minutes = Math.floor((ms % HOUR) / MINUTE);
  const seconds = Math.floor((ms % MINUTE) / SECOND);
  
  return `${days}d ${hours}h ${minutes}m ${seconds}s`;
}

// Example: Session timeout
const sessionTimeout = 30 * MINUTE; // 30 minutes
console.log(formatDuration(sessionTimeout)); // "0d 0h 30m 0s"

Time Zone Considerations

// UTC timestamp (always use for storage!)
const utcDate = new Date().toISOString();
// "2025-11-17T15:30:00.000Z"

// Local timestamp (for display only)
const localDate = new Date().toLocaleString('en-US', {
  timeZone: 'America/New_York'
});
// "11/17/2025, 10:30:00 AM"

Best practice: Store timestamps in UTC, convert to local time only for display.

Performance Timing

// Measuring execution time
const start = performance.now();

// Your code here
await heavyOperation();

const end = performance.now();
const durationMs = end - start;

console.log(`Operation took ${durationMs.toFixed(2)}ms`);

Number System Conversions

Decimal, Binary, Hexadecimal, Octal

Developers frequently work with different number systems for colors, permissions, IP addresses, and low-level operations.

Decimal to Other Bases:

const decimal = 255;

const binary = decimal.toString(2);     // "11111111"
const hex = decimal.toString(16);       // "ff"
const octal = decimal.toString(8);      // "377"

// With prefix
const hexColor = `#${decimal.toString(16).padStart(2, '0')}`; // "#ff"

Other Bases to Decimal:

const binary = "11111111";
const decimal = parseInt(binary, 2);    // 255

const hex = "ff";
const decimalFromHex = parseInt(hex, 16); // 255

const octal = "377";
const decimalFromOctal = parseInt(octal, 8); // 255

RGB to Hex (and vice versa)

// RGB to Hex
function rgbToHex(r, g, b) {
  return '#' + [r, g, b]
    .map(x => x.toString(16).padStart(2, '0'))
    .join('');
}

rgbToHex(255, 99, 71); // "#ff6347" (tomato)

// Hex to RGB
function hexToRgb(hex) {
  const result = /^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(hex);
  return result ? {
    r: parseInt(result[1], 16),
    g: parseInt(result[2], 16),
    b: parseInt(result[3], 16)
  } : null;
}

hexToRgb('#ff6347'); // { r: 255, g: 99, b: 71 }

Unix File Permissions

// Octal to permission string
function permissionsToString(octal) {
  const modes = ['---', '--x', '-w-', '-wx', 'r--', 'r-x', 'rw-', 'rwx'];
  const owner = modes[parseInt(octal[0])];
  const group = modes[parseInt(octal[1])];
  const others = modes[parseInt(octal[2])];
  return owner + group + others;
}

permissionsToString('755'); // "rwxr-xr-x"
permissionsToString('644'); // "rw-r--r--"

IP Address Conversions

// IPv4 to Integer
function ipToInt(ip) {
  return ip.split('.').reduce((acc, octet) => {
    return (acc << 8) + parseInt(octet);
  }, 0) >>> 0; // Unsigned 32-bit
}

ipToInt('192.168.1.1'); // 3232235777

// Integer to IPv4
function intToIp(int) {
  return [
    (int >>> 24) & 0xFF,
    (int >>> 16) & 0xFF,
    (int >>> 8) & 0xFF,
    int & 0xFF
  ].join('.');
}

intToIp(3232235777); // "192.168.1.1"

Common Developer Scenarios

API Rate Limiting

// Rate limit: 100 requests per minute
const RATE_LIMIT = 100;
const WINDOW = 60 * 1000; // 1 minute in ms

// Calculate delay between requests
const delayMs = WINDOW / RATE_LIMIT; // 600ms

// Better approach: requests per second
const requestsPerSecond = RATE_LIMIT / 60; // 1.67 req/s

Database Query Optimization

-- Bad: String date comparison
SELECT * FROM orders 
WHERE created_at > '2025-01-01';

-- Good: Unix timestamp comparison (faster indexing)
SELECT * FROM orders 
WHERE created_at_unix > 1735689600;

Cache Expiration

// Set cache TTL (Time To Live)
const CACHE_TTL = {
  short: 5 * 60,        // 5 minutes (in seconds)
  medium: 1 * 60 * 60,  // 1 hour
  long: 24 * 60 * 60    // 24 hours
};

await redis.setex(key, CACHE_TTL.medium, value);

Memory Budget Calculations

// Estimate memory for in-memory cache
const avgObjectSize = 2 * 1024; // 2 KiB per object
const maxObjects = 10_000;
const estimatedMemory = avgObjectSize * maxObjects;

console.log(`Cache will use approximately ${formatBytes(estimatedMemory)}`);
// "19.53 MiB"

Common Pitfalls and Solutions

1. Floating Point Precision

// Problem
0.1 + 0.2; // 0.30000000000000004 ❌

// Solution: Use integer math
const cents = (10 + 20); // 30 cents
const dollars = cents / 100; // 0.30 ✅

// Or use libraries
import Decimal from 'decimal.js';
new Decimal(0.1).plus(0.2).toNumber(); // 0.3 ✅

2. Integer Overflow

// JavaScript safe integer limit
Number.MAX_SAFE_INTEGER; // 9,007,199,254,740,991

// Problem: Large numbers lose precision
const big = 9007199254740992;
big + 1 === big; // true ❌

// Solution: Use BigInt
const bigInt = 9007199254740992n;
bigInt + 1n; // 9007199254740993n ✅

3. Timezone-Aware Dates

// Problem: Date parsing assumes local timezone
new Date('2025-11-17'); // Midnight in LOCAL timezone ❌

// Solution: Use ISO format with UTC
new Date('2025-11-17T00:00:00Z'); // Midnight UTC ✅

// Or use libraries
import { parseISO } from 'date-fns';
parseISO('2025-11-17');

4. Bitwise Operations on Negative Numbers

// Problem: JavaScript uses 32-bit signed integers for bitwise ops
-1 >> 1; // -1 (sign extension) ❌

// Solution: Use unsigned right shift
-1 >>> 1; // 2147483647 ✅

Tools and Resources

Online Converters:

  • Unit Converter: Quick conversions for bytes, time, numbers
  • Color Picker: RGB/Hex conversions with visual feedback
  • Timestamp Converter: Unix time to human-readable dates

Programming Libraries

JavaScript:

// Date/time
import { formatDistance, formatDuration } from 'date-fns';

// Bytes
import bytes from 'bytes';
bytes('1GB'); // 1073741824

// Numbers
import numeral from 'numeral';
numeral(1000).format('0.0a'); // "1.0k"

Python:

# Bytes
from humanize import naturalsize
naturalsize(1024**3) # "1.1 GB"

# Time
from datetime import timedelta
td = timedelta(hours=2, minutes=30)
td.total_seconds() # 9000.0

Best Practices Summary

Always specify units in variable names: timeoutMs, fileSizeBytes, durationSeconds

Use constants for conversions: const MB = 1024 * 1024;

Store times in UTC, display in local

Use BigInt for large integers (> 53 bits)

Document which unit system you’re using (binary vs decimal)

Validate input ranges before conversions

Use typed languages (TypeScript) to catch unit mismatches

Conclusion

Unit conversions are a fundamental skill for developers. Whether you’re optimizing database storage, debugging timestamp issues, or calculating network throughput, understanding these conversions helps you write better code and make more accurate technical decisions.

Remember to:

  • Use the right precision for your use case
  • Document units clearly
  • Be aware of common pitfalls
  • Use established libraries when possible

Need quick conversions? Try our Unit Converter tool for instant data storage, time, and number system conversions.

Tags: #Development #Programming #UnitConversion #DataStorage #TimeZones #BestPractices

Found this helpful? Try our free tools!

Explore Our Tools →