Berry int() now accepts hex strings

This commit is contained in:
Stephan Hadinger 2022-06-03 21:51:20 +02:00
parent 6ab509576a
commit 7232f5865d
4 changed files with 48 additions and 28 deletions

View File

@ -168,21 +168,9 @@ static int check_next(blexer *lexer, int c)
return 0;
}
static int char2hex(int c)
{
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 0x0A;
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 0x0A;
}
return -1;
}
static int check2hex(blexer *lexer, int c)
{
c = char2hex(c);
c = be_char2hex(c);
if (c < 0) {
be_lexerror(lexer, "invalid hexadecimal number");
}
@ -333,7 +321,7 @@ static bint scan_hexadecimal(blexer *lexer)
{
bint res = 0;
int dig, num = 0;
while ((dig = char2hex(lgetc(lexer))) >= 0) {
while ((dig = be_char2hex(lgetc(lexer))) >= 0) {
res = ((bint)res << 4) + dig;
next(lexer);
++num;

View File

@ -231,29 +231,54 @@ const char* be_pushvfstr(bvm *vm, const char *format, va_list arg)
return concat2(vm);
}
int be_char2hex(int c)
{
if (c >= '0' && c <= '9') {
return c - '0';
} else if (c >= 'a' && c <= 'f') {
return c - 'a' + 0x0A;
} else if (c >= 'A' && c <= 'F') {
return c - 'A' + 0x0A;
}
return -1;
}
/*******************************************************************
* the function be_str2int():
* >>-+------------+--+-----+----digits----><
* '-whitespace-' +- + -+
* '- - -'
* >>-+------------+--+--+-----+----digits-------+----------------><
* '-whitespace-' | +- + -+ |
* | '- - -' |
* | |
* +- 0x or 0X ---hex_digits--+
*
*******************************************************************/
BERRY_API bint be_str2int(const char *str, const char **endstr)
{
int c, sign;
bint sum = 0;
skip_space(str);
sign = c = *str++;
if (c == '+' || c == '-') {
c = *str++;
if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
/* hex literal */
str += 2; /* skip 0x or 0X */
while ((c = be_char2hex(*str++)) >= 0) {
sum = sum * 16 + c;
}
return sum;
} else {
/* decimal literal */
sign = c = *str++;
if (c == '+' || c == '-') {
c = *str++;
}
while (is_digit(c)) {
sum = sum * 10 + c - '0';
c = *str++;
}
if (endstr) {
*endstr = str - 1;
}
return sign == '-' ? -sum : sum;
}
while (is_digit(c)) {
sum = sum * 10 + c - '0';
c = *str++;
}
if (endstr) {
*endstr = str - 1;
}
return sign == '-' ? -sum : sum;
}
/*******************************************************************

View File

@ -19,6 +19,7 @@ bstring* be_strcat(bvm *vm, bstring *s1, bstring *s2);
int be_strcmp(bstring *s1, bstring *s2);
bstring* be_num2str(bvm *vm, bvalue *v);
void be_val2str(bvm *vm, int index);
int be_char2hex(int c);
size_t be_strlcpy(char *dst, const char *src, size_t size);
const char* be_splitpath(const char *path);
const char* be_splitname(const char *path);

View File

@ -6,3 +6,9 @@ class Test_int
end
t=Test_int()
assert(int(t) == 42)
#- int can parse hex strings -#
assert(int("0x00") == 0)
assert(int("0X1") == 1)
assert(int("0x000000F") == 15)
assert(int("0x1000") == 0x1000)