1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20 #include <stdbool.h>
21 #include "util/mcumgr_util.h"
22
23 int
ull_to_s(unsigned long long val,int dst_max_len,char * dst)24 ull_to_s(unsigned long long val, int dst_max_len, char *dst)
25 {
26 unsigned long copy;
27 int digit;
28 int off;
29 int len;
30
31 /* First, calculate the length of the resulting string. */
32 copy = val;
33 for (len = 0; copy != 0; len++) {
34 copy /= 10;
35 }
36
37 /* A value of 0 still requires one character ("0"). */
38 if (len == 0) {
39 len = 1;
40 }
41
42 /* Ensure the buffer can accommodate the string and terminator. */
43 if (len >= dst_max_len - 1) {
44 return -1;
45 }
46
47 /* Encode the string from right to left. */
48 off = len;
49 dst[off--] = '\0';
50 do {
51 digit = val % 10;
52 dst[off--] = '0' + digit;
53
54 val /= 10;
55 } while (val > 0);
56
57 return len;
58 }
59
60 int
ll_to_s(long long val,int dst_max_len,char * dst)61 ll_to_s(long long val, int dst_max_len, char *dst)
62 {
63 unsigned long long ull;
64
65 if (val < 0) {
66 if (dst_max_len < 1) {
67 return -1;
68 }
69
70 dst[0] = '-';
71 dst_max_len--;
72 dst++;
73
74 ull = -val;
75 } else {
76 ull = val;
77 }
78
79 return ull_to_s(ull, dst_max_len, dst);
80 }
81