0

I want to insert the values from vector<uint32_t> A into vector<uint8_t> B. I am doing this way.

#include <stdio.h>
#include <vector>
#include <bits/stdc++.h>
using namespace std;
int main()
{

    std::vector<uint8_t> B;
    std::vector<uint32_t> A;

    B.push_back(3);
    B.push_back(5);

    A.push_back(2344);
    A.push_back(4224);

    B.insert(B.end(), A.begin(), A.end());

    for (int i = 0; i < B.size(); i++)
    {
        cout << unsigned(B[i]) << " ";   
    }

    return 0;
}
 

Output : 3 5 40 128 // How 2344, 4224 got converted into 40 , 128 ?

I want to know how the values from A are getting into B. Also Is it possible to get back the original value from the output ?

Nicol Bolas
  • 449,505
  • 63
  • 781
  • 982
  • 1
    Please don't spam the tags, this not a `c` question. – Pablo Oct 22 '22 at 02:33
  • 2
    2344 (base10) = 0x928, 4224 (base 10) = 0x1080... 0x28 = 40 (base 10) and 0x80 = 128 (base 10)... In short, no... Once the code has discarded the high-order bits, you cannot recover them from "the output"... – Fe2O3 Oct 22 '22 at 02:38
  • `uint32_t` and `uint8_t` have different lengths and different value ranges. `uint32_t` had 4 bytes and `uint8_t` has only 1 byte. An `uint8_t` variable can only hold numbers 0 to 255, while `uint32_t` can hold much bigger numbers. Once you convert `uint32_t` into `uint8_t`, data will be overflow and 3 bytes will be lost, and you cannot get them back because they are not backed up anywhere. That means there no way to convert it from `uint8_t` back to `uint32_t`. – sxu Oct 22 '22 at 03:35
  • *"I want to know how the values from A are getting into B"* -- umm, the line `B.insert(B.end(), A.begin(), A.end());`? What else was this line supposed to do? – JaMiT Oct 22 '22 at 03:37
  • You might want to focus on a simpler situation. You are confused about a `uint32_t` value becoming a `uint8_t` value, right? So drop the vectors. Try `int main() { uint32_t a = 2344; uint8_t b = a; std::cout << b; }` -- is this enough to reproduce the conversion to 40 (a.k.a. the low 8 bits of 2344)? – JaMiT Oct 22 '22 at 03:40
  • Hmm... not finding a duplicate yet. There must be one out there. In the meantime, see what happens if you change `2344` to `2600` (or to `2856` or to `2856+256`). Then get back to us about how likely it is that you can get back the original value from `40`. – JaMiT Oct 22 '22 at 03:48
  • [Why should I not #include ?](https://stackoverflow.com/q/31816095/995714), [Why is "using namespace std;" considered bad practice?](https://stackoverflow.com/q/1452721/995714) – phuclv Oct 22 '22 at 03:53

0 Answers0