Cast int as an array of bytes in C ++

I am trying to use the LSB search method proposed by Andrei Grant in answer to this question: Position of the minimum significant bit set

However, this leads to a segmentation error. 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 read that it is not recommended to use "C-Style" in C ++. Should I use reinterpret_cast<Byte*>(value) instead? However, this still leads to a segmentation error.

+4
source share
5 answers

Use this:

 (Byte*) &value; 

You do not want the pointer pointing to 300, you want the pointer to be where 300 is stored. Thus, you use the address of the & operator to get the address value .

+11
source

While Eric answered your general question, as a continuation, I would say strongly - yes, reinterpret_cast should be used, not in the C style.

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

The string should be: Byte * byteArray = (Byte *) & value;

You do not need to put (void *) in front of you.

-Chert

+1
source
 char *array=(char*)(void*)&value; 

Basically you take a pointer to the beginning of a string and convert it to a pointer to a byte.

0
source

@Erik has already fixed your main problem, but there is a thin one that you have. If you are looking for only the least significant bit You donโ€™t have to worry about casting at all.

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

Source: https://habr.com/ru/post/1343057/


All Articles