Using unsigned char array to store memory efficiently [closed] - c++

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 3 years ago.
Improve this question
I was looking for an efficient way to store memory, so I realized that an unsigned char uses only one byte of memory. Thinking about it I made a small program that obtains the size of bytes of each variable.
int main() {
int myInt = 10;
long long myLongLong = 10;
unsigned char charArray1[] = { 10, 10, 10, 10 };
unsigned char charArray2[] = { 10, 10, 10, 10, 10, 10, 10, 10 };
std::cout << "Using sizeof () we get:" << std::endl;
std::cout << "myInt -> " << sizeof(myInt) << std::endl;
std::cout << "myLongLong -> " << sizeof(myLongLong) << std::endl;
std::cout << "charArray1 -> " << sizeof(charArray1) << std::endl;
std::cout << "charArray2 -> " << sizeof(charArray2) << std::endl;
return 0;
}
Output:
Using sizeof () we get:
myInt -> 4
myLongLong -> 8
charArray1 -> 4
charArray2 -> 8
Is it correct to say that I can store bytes in an unsigned char array? If correct, how can I get some matrix elements from unsigned char and assign them to a variable?
Example: If an integer occupies 4 bytes in memory, I can get 4 elements from the unsigned char array and assign it to an integer.

Is it correct to say that I can store bytes in an unsigned char array?
Yes.
If an integer occupies 4 bytes in memory, I can get 4 elements from the unsigned char array and assign it to an integer.
If and only if the array contains the bytes of the integer in the exact same format as the system uses natively, then you can do this:
static_assert(sizeof myInt == sizeof charArray1);
std::memcpy(&myInt, charArray1, sizeof myInt);
If the format isn't the same, then it is still possible to calculate the value as long as you know what the bytes represent.

Related

Regarding Bit Fields in Structure and Union

When using bit fields inside structures like:
struct abc{
int a:3;
unsigned int b:1;
} t;
So, my question is, do variables (with set bit-fields) share the same memory space even inside structures? Because when I saw their representation it looked like - first, a will have 3 bits(from LSB) then 1 bit for b (MSB) and all in one 4-byte(32 bits) memory space.
In case of Unions:
typedef union abc {
unsigned int a:32;
int f:1;
} t;
int main()
{ t q;
q.a = (unsigned int)(pow(2,32)-1);
q.f = 1;
cout << sizeof(t) << endl;
cout << q.a << " " << q.f << endl;
return 0;
}
First of all, the sizeof() operator returns 4 bytes as the maximum size for this union
and as 32 bits are set for variable 1 then how can it even manage space for variable b?
Thank you for reading till the end, I'll really appreciate your answers.

Reading values from binary file stored in char array with reinterpret_cast (C++)

I am trying to read in a binary file in a known format. I want to find the most efficient way to extract values from it. My ideas are:
Method 1: Read each value into a new char array then get it into the correct data type. For the first 4 byte positive int, I bitshift the values accordingly and assign to an integer as below.
Method 2: Keep the whole file in a char array, then create pointers to different parts of it. In the code below I am trying to point to these first 4 bytes and use reinterpret_cast to interpret them as an integer when I dereference the variable 'bui'.
But the ouput from this code is:
11000000001100000000110000000011
3224374275
00000011000011000011000011000000
51130560
My questions are
why does the endianness get swapped using my method 2 and how do I point to it correctly?
which method is more efficient? I need all of the file, and the file contains other data types too so I will need to write different methods to interpret them if using method 1. I was assuming I could just define different type pointers if using method 2 without doing extra work!
Thanks
#include <iostream>
#include <bitset>
int main(void){
unsigned char b[4];
//ifs.read((char*)b,sizeof(b));
//let's pretend the following 4 bytes are read in representing the number 3224374275:
b[0] = 0b11000000;
b[1] = 0b00110000;
b[2] = 0b00001100;
b[3] = 0b00000011;
//method 1:
unsigned int a = 0; //4 byte capacity
a = b[0] << 24 | b[1] << 16 | b[2] << 8 | b[3];
std::bitset<32> xm1(a);
std::cout << xm1 << std::endl;
std::cout << a << std::endl;
//method 2;
unsigned int* bui = reinterpret_cast<unsigned int*>(b);
std::bitset<32> xm2(*bui);
std::cout << xm2 << std::endl;
std::cout << *bui << std::endl;
}

Why does conceptual storage allocation differ from the actual? [duplicate]

This question already has answers here:
Pointer subtraction confusion
(8 answers)
Closed 6 years ago.
I have a puzzling question (at least for me)
Say I declare an integer array:
int arr[3];
Conceptually, what happens in the memory is that, at compile time, 12 bytes are allocated to store 3 consecutive integers, right? (Here's an illustration)
Based on the illustration, the sample addresses of
arr[0] is 1000,
arr[1] is 1004, and
arr[2] is 1008.
My question is:
If I output the difference between the addresses of arr[0] and arr[1]:
std::cout << &arr[1] - &arr[0] << std::endl;
instead of getting 4,
I surprisingly get 1.
Can anybody explain why it resulted to that output?
PS: On my computer, an int is 4 bytes.
Pointer arithmetic automatically divides the value by the size of the base type so this is not surprising at all since one would expect to get 4 / 4 which is 1. Cast to unsignd char * to see the difference.
#include <iostream>
int
main(void)
{
int arr[2];
std::cout << &arr[1] - &arr[0] << std::endl;
std::cout << reinterpret_cast<unsigned char *>(&arr[1]) -
reinterpret_cast<unsigned char *>(&arr[0]) << std::endl;
return 0;
}

Why can't I store a small integer in a uint8_t type? [duplicate]

This question already has answers here:
uint8_t can't be printed with cout
(8 answers)
Closed 7 years ago.
If I store the number 2 in a uint8_t type and try to print it I get nothing. Surely an 8 bit integer can store the number 2. What am I missing?
Example code:
#include <iostream>
#include <cstdint>
int main() {
std::uint8_t x = 2;
std::cout << "x = " << x << "\n";
}
Output:
x =
uint8_t will usually be a typedef for unsigned char, and will be printed as a character.
2 is some unprintable character value though, so you don't get any meaningful output.
You can use +x to promote x to an integer, and it will be printed as such.

Unable to understand struct to char* conversion [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I have defined a struct data and assigning it to a char*. However the size of strlen function always gives result as 1 and cout doesn't show anything. Here is my code:
struct data
{
int x;
int y;
};
int main()
{
data d;
d.x = 10;
d.y = 20;
char *ch = (char*)&d;
cout <<"Length:" strlen(ch) << endl;
cout << ch << endl;
}
The output is:
Length: 1
Please help me in understanding what's going on ?
The strlen function counts all bytes in the passed string until it finds the character '\0'. This character is the same as the integer 0.
So what the call to strlen is count the number of bytes until it finds a zero, and in your case the zero happens to be in the second byte of the structures binary representation, meaning that the "string length" is one.
The only thing that you can deduce from this is that you are on a little endian system. Other than that, the call is undefined behavior as the "string" isn't actually a string.
The reason it returns 1 is because you are treating the struct as a char array. Doing this you are re-interpreting the contents of the struct - the integer 10, which is probably stored in memory as 0x0A000000 - as a string. And that yields a length of 1 (only 1 non-zero value before a null-character in the array)
Even though you're trying to treat something as a string which isn't a string, if all you want to do is print out the values in the struct, you can do something like:
struct data
{
int x;
int y;
};
int main()
{
data d;
d.x = 10;
d.y = 20;
cout << "x is " << d.x << ", y is " << d.y << endl;
}
Why are you trying to treat that struct as a string?