简体   繁体   English

在Linux 32位上以36为基数的strtoull长时间溢出无符号

[英]strtoull with base 36 overflowing unsigned long long on Linux 32bit

Anyone know why using strtoull will overlow an unsigned long long? 任何人都知道为什么使用strtoull会使无符号的long long变长吗? The value of "x" is 12 when I make the call, so I'm trying to convert a 12 digit base 36 num to unsigned long long. 拨打电话时,“ x”的值为12,因此我试图将12位基数36 num转换为unsigned long long。

This should work right? 这应该工作对吗? It doesn't matter whether I compile 32 or 64bit. 我编译32位还是64位都没有关系。 I'm using g++ on redhat. 我在Redhat上使用g ++。

buffer is a char* 缓冲区是一个字符*

char *strPtr = buffer + ORDERIDOFFSET;
char *endPtr = strPtr + ORDERIDLENGTH;
long x = long((endPtr)) - long(buffer + ORDERIDOFFSET);
unsigned long long orderid = strtoull((buffer + ORDERIDOFFSET), &(endPtr), 36);

Thanks! 谢谢!

You seem to be under the misapprehension that endptr is an input parameter to strtoull , which tells it how long the input string is. 你似乎是看错下endptr是一个输入参数strtoull ,告诉它输入的字符串有多长。 It is not. 它不是。 It is an output parameter, which strtoull uses to tell you the first character it could not convert. 它是一个输出参数, strtoull用来告诉您无法转换的第一个字符。

I presume that your buffer is not nul-terminated; 我认为您的缓冲区没有终止。 probably there is an alphanumeric character following your 12-digit base-36 number. 您的12位36进制数字后面可能有一个字母数字字符。

By the way, imho, x would be better computed as endPtr - strPtr . 顺便说一句,恕我直言,将x更好地计算为endPtr - strPtr Casting to long is not really correct. 铸造于long是不是真的正确。

You appear to be trying to use endPtr as an input parameter. 您似乎正在尝试使用endPtr作为输入参数。 std::strtoull takes the second parameter as an output parameter. std::strtoull将第二个参数作为输出参数。

You may find it more robust to use std::stoull instead of std::strtoull : 您可能会发现使用std::stoull而不是std::strtoull更健壮:

char *strPtr = buffer + ORDERIDOFFSET;
char *endPtr = strPtr + ORDERIDLENGTH; // assuming ORDERIDLENGTH takes you 1 passed the end of the actual ID string
std::string s(strPtr, endPtr);
unsigned long long orderid = std::stoull(s, nullptr, 36);

Additionally, 另外,

long x = long((endPtr)) - long(buffer + ORDERIDOFFSET);

is not portable to 64-bit systems (you would truncate the address). 不能移植到64位系统(您将截断地址)。 I'm pretty sure you want 我很确定你要

std::size_t x = endPtr - strPtr;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM