java代码
public static String formatFileSize(long size) {
if (size < 1024) return size + " B";
int z = (63 - Long.numberOfLeadingZeros(size)) / 10;
return String.format("%.1f %sB", (double) size / (1L << (z * 10)), " KMGTPE".charAt(z));
}
php代码
function formatFileSize($size) {
if ($size < 1024) return $size . " B";
$z = (63 - (int)log($size, 2)) / 10;
return sprintf("%.1f %sB", $size / (1 << ($z * 10)), " KMGTPE"[$z]);
}
golang代码
func formatFileSize(size int64) string {
if size < 1024 {
return fmt.Sprintf("%d B", size)
}
z := (63 - int(math.Log2(float64(size)))) / 10
return fmt.Sprintf("%.1f %cB", float64(size)/(1<<uint(z*10)), " KMGTPE"[z])
}
C代码
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <string.h>
char* formatFileSize(long long size) {
char *output = (char*)malloc(20); // 分配足够的内存以存储结果字符串
if (output == NULL) {
fprintf(stderr, "内存分配失败\n");
exit(1);
}
if (size < 1024) {
sprintf(output, "%lld B", size);
} else {
int z = (63 - __builtin_clzll(size)) / 10;
sprintf(output, "%.1f %cB", (double)size / (1LL << (z * 10)), " KMGTPE"[z]);
}
return output;
}
int main() {
// 测试示例
char *result = formatFileSize(123456789); // 117.7 MB
printf("%s\n", result);
free(result); // 释放动态分配的内存
return 0;
}