Reading 64 bit integers binary file

时间:2018-01-23 19:17:13

标签: c++ file visual-c++

I am asking for the correct way to read a binary files by taking blocks that are 64 bits of size. I am currently doing it this way :

    uint64_t uInt;
    char c;
    if(istr)
  {
    while (true)
    {
        istr.get(c);
        if (istr.eof())
            break;
        istr.putback(c);
        istr.read(reinterpret_cast<char *>(&uInt), sizeof(uInt));
        tea.encryptBlock(uInt, ostr);
    }
  }

istr and ostr are streams to files I want to read/write to. While it works for the biggest part of the file while debugging I used binary viewer and it seems like that the last 32 bits are wrong(i need them because i am trying to do encryption/decryption using the tiny encryption algorithm which uses 64 bit block split into 2 halves). I am not sure what is causing this problem and I was thinking that maybe I should try to read only characters and then combine them using something like this:

  int64_t charTo64bitNum(char *a) {
  int64_t n = 0;
  n = (((int64_t)a[0] << 56) & 0xFF00000000000000U)
    | (((int64_t)a[1] << 48) & 0x00FF000000000000U)
    | (((int64_t)a[2] << 40) & 0x0000FF0000000000U)
    | (((int64_t)a[3] << 32) & 0x000000FF00000000U)
    | ((a[4] << 24) & 0x00000000FF000000U)
    | ((a[5] << 16) & 0x0000000000FF0000U)
    | ((a[6] << 8) & 0x000000000000FF00U)
    | (a[7] & 0x00000000000000FFU);
    return n;
 }

but it doesn't seem to work.

1 个答案:

答案 0 :(得分:0)

Try to read a chunk of 8 bytes from your file to uint8_t buff[8], and then do

   uint8_t buff[] = { 0,1,2,3,4,5,6,7 };
   uint64_t val = (uint64_t)buff[7] 
                  | ((uint64_t)buff[6] << 8) 
                  | ((uint64_t)buff[5] << 16) 
                  | ((uint64_t)buff[4] << 24) 
                  | ((uint64_t)buff[3] << 32) 
                  | ((uint64_t)buff[2] << 40) 
                  | ((uint64_t)buff[1] << 48) 
                  | ((uint64_t)buff[0] << 56);
  // buff == 0x0001020304050607LL
  // to split:
  uint32_t val1 = (uint32_t)(val & ((1 << 32) - 1));
  uint32_t val2 = (uint32_t)(val >> 32);

Update: reversed indices

//[0]83 [1]111 [2]109 [3]101 [4]32 [5]116 [6]101 [7]120
uint8_t arr[] = { 83, 111, 109, 101, 32, 116, 101, 120 };
uint64_t expected = 8675467939688574803;
uint64_t val = (uint64_t)arr[0] 
    | ((uint64_t)arr[1] << 8) 
    | ((uint64_t)arr[2] << 16) 
    | ((uint64_t)arr[3] << 24) 
    | ((uint64_t)arr[4] << 32) 
    | ((uint64_t)arr[5] << 40) 
    | ((uint64_t)arr[6] << 48) 
    | ((uint64_t)arr[7] << 56);