1 // SPDX-License-Identifier: GPL-2.0
3 * Copyright (c) 2000 Silicon Graphics, Inc.
8 #include "str_to_bytes.h"
10 /****************************************************************************
13 * Computes the number of bytes described by string s. s is assumed to be
14 * a base 10 positive (ie. >= 0) number followed by an optional single
15 * character multiplier. The following multipliers are supported:
21 * K 1024 * sizeof(long)
23 * M 2^20 (1048576 * sizeof(long)
25 * G 2^30 (1073741824) * sizeof(long)
27 * for instance, "1k" and "1024" would both cause str_to_bytes to return 1024.
29 * Returns -1 if mult is an invalid character, or if the integer portion of
30 * s is not a positive integer.
32 ****************************************************************************/
35 #define B_MULT DEV_BSIZE /* block size */
39 #define K_MULT 1024 /* Kilo or 2^10 */
40 #define M_MULT 1048576 /* Mega or 2^20 */
41 #define G_MULT 1073741824 /* Giga or 2^30 */
42 #define T_MULT 1099511627776 /* tera or 2^40 */
52 nconv = sscanf(s, "%f%c%c", &num, &mult, &junk);
53 if (nconv == 0 || nconv == 3 )
61 return (int)(num * (float)B_MULT);
63 return (int)(num * (float)K_MULT);
65 return (int)((num * (float)K_MULT) * sizeof(long));
67 return (int)(num * (float)M_MULT);
69 return (int)((num * (float)M_MULT) * sizeof(long));
71 return (int)(num * (float)G_MULT);
73 return (int)((num * (float)G_MULT) * sizeof(long));
87 nconv = sscanf(s, "%f%c%c", &num, &mult, &junk);
88 if (nconv == 0 || nconv == 3 )
96 return (long)(num * (float)B_MULT);
98 return (long)(num * (float)K_MULT);
100 return (long)((num * (float)K_MULT) * sizeof(long));
102 return (long)(num * (float)M_MULT);
104 return (long)((num * (float)M_MULT) * sizeof(long));
106 return (long)(num * (float)G_MULT);
108 return (long)((num * (float)G_MULT) * sizeof(long));
115 * Force 64 bits number when compiled as a 32-bit binary.
116 * This allows for a number bigger than 2G.
127 nconv = sscanf(s, "%lf%c%c", &num, &mult, &junk);
128 if (nconv == 0 || nconv == 3 )
132 return (long long)num;
136 return (long long)(num * (float)B_MULT);
138 return (long long)(num * (float)K_MULT);
140 return (long long)((num * (float)K_MULT) * sizeof(long long));
142 return (long long)(num * (float)M_MULT);
144 return (long long)((num * (float)M_MULT) * sizeof(long long));
146 return (long long)(num * (float)G_MULT);
148 return (long long)((num * (float)G_MULT) * sizeof(long long));
156 main(int argc, char **argv)
161 fprintf(stderr, "missing str_to_bytes() parameteres\n");
165 for (ind=1; ind<argc; ind++) {
167 printf("str_to_bytes(%s) returned %d\n",
168 argv[ind], str_to_bytes(argv[ind]));
170 printf("str_to_lbytes(%s) returned %ld\n",
171 argv[ind], str_to_lbytes(argv[ind]));
173 printf("str_to_llbytes(%s) returned %lld\n",
174 argv[ind], str_to_llbytes(argv[ind]));