在C ++中将int转换为字节数组

时间:2011-03-09 18:45:03

标签: c++ casting byte segmentation-fault

我正在尝试使用实现Andrew Grant建议的LSB查找方法来回答这个问题:Position of least significant bit that is set

然而,它导致了分段错误。这是一个展示问题的小程序:

#include <iostream>

typedef unsigned char Byte;

int main()  
{  
    int value = 300;  
    Byte* byteArray = (Byte*)value;  
    if (byteArray[0] > 0)  
    {  
        std::cout<< "This line is never reached. Trying to access the array index results in a seg-fault." << std::endl;  
    }  
    return 0;  
}  

我做错了什么? 我已经读过在C ++中使用'C-Style'强制转换是不好的做法。我应该使用reinterpret_cast<Byte*>(value)吗?但是,这仍会导致分段错误。

5 个答案:

答案 0 :(得分:11)

使用此:

(Byte*) &value;

您不希望指向地址300的指针,您想要指向存储300的指针。因此,您使用地址运算符&来获取value的地址。

答案 1 :(得分:6)

虽然Erik回答了你的整体问题,但我会强调说明 - 是的,应该使用reinterpret_cast而不是C风格的演员。

Byte* byteArray = reinterpret_cast<Byte*>(&value);

答案 2 :(得分:1)

该行应该是: 字节* byteArray =(字节*)&amp; value;

你不应该把(void *)放在它前面。

-Chert

答案 3 :(得分:0)

char *array=(char*)(void*)&value;

基本上你会指向字符串的开头并将其重新转换为指向字节的指针。

答案 4 :(得分:0)

@Erik已经修复了你的主要问题,但是你还有一个微妙的问题。如果您只是寻找最不重要的,则根本不需要使用演员表。

int main()
{
    int value = 300;       
    if (value & 0x00000001)       
    {           
        std::cout<< "LSB is set" << std::endl;
    }
    return 0;
}
相关问题