I have some file. In the loop I write a 128 bit block from it, into an array of 4 * 32 bits (say, for subsequent AES encryption).

It is necessary to implement the method of addition 2 (one bit + zeros to the end of the block). I wrote this code (of course, inside the loop as the file is read):

std::array<int32_t, 4> block; input.read(reinterpret_cast<char *>(&block), sizeof block); if (static_cast<unsigned long>(input.gcount()) < sizeof block) { int16_t *tmp = reinterpret_cast<int16_t *>(block.begin()); tmp[input.gcount() - 1] = 0x1000; for (auto i = input.gcount(); i < 16; ++i) { tmp[i] = 0x0000; } } 

But it turns out incorrectly - too much is cut off, or the data from the previous block generally gets into the block. What have I done wrong? Maybe there is a more elegant method?

  • The nullification cycle is great. Up to 16 iterations of int16_t with a block size of 128 bits. Those. going beyond the boundaries, which means UB. Well, std::array somehow out of place here. Plus, what happens if gcount returns 0? Another go beyond the boundaries. - 伪位蔚蠂慰位蠀蟿
  • @alexolut, what std::array didn't please? - ixSci
  • @ixSci at least by the fact that the type of iterator is cast to a pointer. Although the implementation defined iterator. - 伪位蔚蠂慰位蠀蟿
  • @alexolut, it means you need begin to replace with [0] , but this is not a reason to refuse std::array . - ixSci
  • @ixSci well maybe. We must continue to look at how it is used there. Personally, I would declare an ordinary array, for so much shorter. And here's another thing that confused me so much is the hodgepodge of B styles and pluses. If we use std :: array, then the size must be obtained through the size member, and not sizeof. - 伪位蔚蠂慰位蠀蟿

1 answer 1

 int n = input.gcount(); if (n < 16) { block[n++] = 0x80; for (int i = n; i < 16; i++) block[i] = 0; } 

Here the bit is 0x80, and the byte type block (uint8_t)