这可能是你在追求什么。
int get_value_from_array(char* buffer, int byte1, int byte2)
{
int j = 0;
assert(buffer != 0);
assert(byte1 >= 0 && byte2 >= byte1 && (size_t)(byte2 - byte1) < sizeof(int));
for (int i = 0; i < byte2 - byte1; i++)
j += (unsigned char)buffer[byte1+i] << (i*8);
return j;
}
正如我的评论所指出的,你真的不希望分配int *j
出于多种原因,包括“你是不是允许使用malloc()
”和“当在你的问题误用它泄漏内存”。
而且,老实说,在我看到您的问题更新之前,我写了这段代码! assert()
和(unsigned char)
转换是您的原始代码和此代码之间的唯一区别。我不确定你如何得到浮点异常。如果你除以零,你可以得到其中的一个,但是在你的代码中没有明显的分割,更不用说被零除。
您应该回到原始代码并在运行时打印所有信息。或者使用调试器来完成它。
int get_value_from_array(char* buffer, int byte1, int byte2)
{
int j = 0;
printf("-->> %s: %p (%d..%d)\n", __func__, buffer, byte1, byte2);
assert(buffer != 0);
assert(byte1 >= 0 && byte2 >= byte1 && (size_t)(byte2 - byte1) < sizeof(int));
for (int i = 0; i < byte2 - byte1; i++)
{
printf("j0 = 0x%.8X, i = %d, byte = 0x%.2X, "
"add = 0x%.8X, j1 = 0x%.8X\n",
j, i, (unsigned char)buffer[byte1+i],
(unsigned char)buffer[byte1+i] << (i*8),
j + (unsigned char)buffer[byte1+i] << (i*8));
j += (unsigned char)buffer[byte1+i] << (i*8);
}
printf("<<-- %s: 0x%.8X\n", __func__, j);
return j;
}
请注意,打印以换行符结束。在C99中,__func__
是该函数的名称;如果您有C89/C90,则省略,然后删除%s
—或用您的函数名称替换%s
(或用您的函数名称替换为__func__
作为字符串文字:"get_value_from_array"
)。
调试代码写在C89/C90:
int get_value_from_array(char* buffer, int byte1, int byte2)
{
static const char func[] = "get_value_from_array";
int i;
int j = 0;
printf("-->> %s: %p (%d..%d)\n", func, buffer, byte1, byte2);
assert(buffer != 0);
assert(byte1 >= 0 && byte2 >= byte1 && (size_t)(byte2 - byte1) < sizeof(int));
for (i = 0; i < byte2 - byte1; i++)
{
printf("j0 = 0x%.8X, i = %d, byte = 0x%.2X, "
"add = 0x%.8X, j1 = 0x%.8X\n",
j, i, (unsigned char)buffer[byte1+i],
(unsigned char)buffer[byte1+i] << (i*8),
j + (unsigned char)buffer[byte1+i] << (i*8));
j += (unsigned char)buffer[byte1+i] << (i*8);
}
printf("<<-- %s: 0x%.8X\n", func, j);
return j;
}
目前尚不清楚你想要做什么,而是'的malloc(的sizeof(int)的)'看起来并不像它足够的空间。 –
您能否提供缓冲区,字节1,字节2和预期j的样本数据?另外,j是一个指向int的指针,你想要返回j的值吗?对于这个问题,你为什么动态分配j? – dsolimano
@iharob tbh我刚刚按照链接上的例子。 –