黑客的喜悦涵盖了sign extension。
对于您的 24 位数字,符号 位是右起第 24 位,如果设置了十六进制值,则为 0x800000。
这本书提出了这些建议:
((x + 0x800000) & 0xFFFFFF) - 0x800000
or
((x & 0xFFFFFF) xor 0x800000) - 0x800000
根据您的问题,我会说您的数字永远不会超过 24 位,因此我将在您的代码中使用第二个选项,如下所示:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
char temp_str[] = "FFFFFF";
long value;
value = strtol(temp_str, NULL, 16);
value = (value ^ 0x800000) - 0x800000; // Notice that I'm not using the & 0xFFFFFF since I assumed that the number won't have more than 24 bits.
printf("value is %ld\n", value);
}
编辑 1:
我担心我最初的答案虽然技术上合理,但并没有回答提出的问题。
谁能帮我理解为什么下面的代码不返回-1?
在我回答时其他人已经涵盖了这个,但无论如何我都会在这里重申。
您的字符串是"FFFFFF",它由 6 个十六进制数字组成。每个十六进制数字代表 4 位,因此您的字符串代表一个 24 位数字。
您的变量long value 是long 类型,通常对应于您的CPU 的字宽(32 位或64 位)。由于现在long 可以是 32 位或 64 位,具体取决于您的体系结构,除非您提供正确的十六进制数字,否则您无法保证获得 -1。
如果您机器上的 long 是 32 位,那么有两件事是正确的:
-
sizeof(long) 将返回 4
- 使用
"FFFFFFFF" 将返回-1
如果您机器上的 long 是 64 位,那么有两件事是正确的:
-
sizeof(long) 将返回 8
- 使用
"FFFFFFFFFFFFFFFF" 将返回 -1
题外话
这让我走上了一条完全不同的道路。我们可以概括这一点,并编写一个为您的机器构造字符串的程序,这样它总是会从字符串中返回 -1。
#include #include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main(void) {
const char* ff = "FF";
char temp[sizeof(long) * 2 + 1]; // Ensure that the string can store enough hex digits so that we can populate the entire width of long. Include 1 byte for '\0'
int i;
long value;
/* Fill the temp array with FF */
for (i = 0; i < sizeof(long); ++i)
{
strcpy(&temp[i * 2], ff);
}
value = strtol(temp, NULL, 16);
printf("value of %s is %ld\n", temp, value);
}
这是获得 -1 结果的不好方法,因为明确的选项是只使用
long value = -1;
但我会假设这只是一个学术练习。