Reputation: 95
I'm really sorry for the wording of the question, it's a bit confusing.
So lets say I have a buffer:
char buffer[4] = {0, 0, 2, 0};
if we convert it all to binary, we get one 32 bit unsigned int:
00000000 00000000 00000010 00000000
The value of it is 512.
So my question is, how do I get to the answer of 512 using c++? Preferably with some library function.
Thanks for any answer, and I'm very sorry if this has been asked before, I couldn't find it.
Upvotes: 7
Views: 381
Reputation: 6018
EDIT: This method "works" but according to some folks it relies on the compiler to allow it as technically it produces undefined behavior. So use at your own risk.
And still another way is to use a union. Depending upon endianess, you will have to order your buffer correctly. See below.
#include <stdio.h>
union u{
unsigned char buffer[4];
unsigned int x;
} u;
int main()
{
u.buffer[0] = 0;
u.buffer[1] = 2;
u.buffer[2] = 0;
u.buffer[3] = 0;
printf("%d\n", u.x);
return 0;
}
As mentioned in a comment, you can use union initialization as well. See below:
#include <stdio.h>
#include <stdint.h>
union u{
uint8_t buffer[4];
uint32_t x;
};
int main()
{
union u u1 = {.buffer = {0,2,0,0} };
printf("%d\n", u1.x);
return 0;
}
Upvotes: -1
Reputation: 428
That's only 512 if you're big endian. You're writing down the binary format as MSB : LSB but that's not how you're representing the bytes in the array buffer. The "LSB" in the array is buffer[0], the little endian representation is shown below.
A portable way of type punning is to actually use memcpy. It's actually all optimized away per this compiler explorer comparison, even the function call.
#include <iostream>
#include <cstdint>
#include <array>
#include <cstring>
std::array<unsigned char, 4> buffer = {0, 2, 0, 0};
template <std::size_t N>
std::uint32_t char_buf_to_int( std::array<unsigned char, N>& b )
{
std::uint32_t i;
std::memcpy( &i, b.data(), b.size() );
return i;
}
int main()
{
std::cout << char_buf_to_int( buffer ) << std::endl;
return 0;
}
Upvotes: 0
Reputation: 9705
You can perform some bitwise operations:
unsigned int converter(const char buffer[4]) {
return (buffer[0] << 24) |
(buffer[1] << 16) |
(buffer[2] << 8) |
(buffer[3]);
}
Upvotes: 8