LMMP 4.3.0
Lamina High-Precision Arithmetic Library
载入中...
搜索中...
未找到
from_hex.c
浏览该文件的文档.
1/**
2 * Copyright (C) 2026 HJimmyK (Jericho Knox)
3 *
4 * This file is part of LMMP.
5 *
6 * LMMP is free software: you can redistribute it and/or modify it
7 * under the terms of the GNU Lesser General Public License as
8 * published by the Free Software Foundation; either version 3 of
9 * the License, or (at your option) any later version.
10 *
11 * This library is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Lesser General Public License for more details.
15 *
16 * You should have received a copy of the GNU Lesser General Public
17 * License along with this library. If not, see
18 * <https://www.gnu.org/licenses/>.
19 *
20 * SPDX-License-Identifier: LGPL-3.0-or-later
21 */
22
23#include "impl/str_conv.h"
24#include "mparam.h"
25#include "lmmp/lmmpn.h"
26
27// ASCII -> nibble 值表,非法字符映射为 0(契约要求输入全为合法十六进制数字)
28static const mp_byte_t lmmp_hex_val_tab[256] = {
29 ['0'] = 0, ['1'] = 1, ['2'] = 2, ['3'] = 3, ['4'] = 4,
30 ['5'] = 5, ['6'] = 6, ['7'] = 7, ['8'] = 8, ['9'] = 9,
31 ['A'] = 10, ['B'] = 11, ['C'] = 12, ['D'] = 13, ['E'] = 14, ['F'] = 15,
32 ['a'] = 10, ['b'] = 11, ['c'] = 12, ['d'] = 13, ['e'] = 14, ['f'] = 15,
33};
34
35mp_size_t lmmp_from_hex_(mp_ptr dst, const char* src, mp_size_t len) {
36 lmmp_param_assert(dst != NULL && src != NULL);
37 do {
38 if (len == 0)
39 return 0;
40 } while (src[--len] == '0');
41 ++len;
42
43 mp_size_t nfull = len >> 4;
44 const char* sp = src;
45 for (mp_size_t i = 0; i < nfull; ++i, sp += 16) {
46 mp_limb_t l = 0;
47 // 组内自高向低读,使得 sp[j] 落在第 j 个 nibble
48 for (int j = 15; j >= 0; --j)
49 l = (l << 4) | lmmp_hex_val_tab[(mp_byte_t)sp[j]];
50 dst[i] = l;
51 }
52
53 int r = (int)(len & 15);
54 if (r) {
55 mp_limb_t l = 0;
56 for (int j = r - 1; j >= 0; --j)
57 l = (l << 4) | lmmp_hex_val_tab[(mp_byte_t)sp[j]];
58 dst[nfull] = l;
59 }
60
61 return nfull + (r != 0);
62}
static const mp_byte_t lmmp_hex_val_tab[256]
Copyright (C) 2026 HJimmyK (Jericho Knox)
mp_limb_t * mp_ptr
定义 lmmp.h:96
uint8_t mp_byte_t
定义 lmmp.h:91
uint64_t mp_size_t
定义 lmmp.h:93
uint64_t mp_limb_t
定义 lmmp.h:92
#define lmmp_param_assert(x)
定义 lmmp.h:509
mp_size_t lmmp_from_hex_(mp_ptr dst, const char *src, mp_size_t len)
十六进制字符串转limb数组 [src,len,16] to [dst,return value,B]