简体   繁体   English

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

[英]Cast int as byte array in C++

I am trying to use implement the LSB lookup method suggested by Andrew Grant in an answer to this question: Position of least significant bit that is set 我正在尝试使用实现安德鲁·格兰特建议的LSB查找方法来回答这个问题: 设置的最低有效位的位置

However, it's resulting in a segmentation fault. 但是,它导致了分段错误。 Here is a small program demonstrating the problem: 这是一个展示问题的小程序:

#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;  
}  

What am I doing wrong? 我究竟做错了什么?
I've read that it's not good practice to use 'C-Style' casts in C++. 我已经读过在C ++中使用'C-Style'强制转换是不好的做法。 Should I use reinterpret_cast<Byte*>(value) instead? 我应该使用reinterpret_cast<Byte*>(value)吗? This still results in a segmentation fault, though. 但是,这仍会导致分段错误。

Use this: 用这个:

(Byte*) &value;

You don't want a pointer to address 300, you want a pointer to where 300 is stored. 您不希望指向地址300的指针,您想要指向存储300的指针。 So, you use the address-of operator & to get the address of value . 因此,您使用address-of运算符&来获取value的地址。

虽然Erik回答了你的整体问题,但作为一个后续内容我会强调说 - 是的,应该使用reinterpret_cast而不是C风格的演员。

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

The line should be: Byte* byteArray = (Byte*)&value; 该行应为:Byte * byteArray =(Byte *)&value;

You should not have to put the (void *) in front of it. 你不应该把(void *)放在它前面。

-Chert -燧石

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

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

@Erik already fixed your primary problem, but there is a subtle one that you still have. @Erik已经解决了你的主要问题,但你仍然有一个微妙的问题。 If you are only looking for the least significant bit , there is no need to bother with the cast at all. 如果您只是寻找最不重要的 ,则根本不需要使用演员。

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

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

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