2

I'm in situation that I have a float64 image stored in a binary format. I would like to read the content of the file and store it in int64, so that I can tonemap it.

The question how would I convert float images into int64 in C++. Here is my approach of reading the file The file is here https://www.mediafire.com/file/ffv6qzvpg05xaja/15_init_image.bin/file

#include <iostream>
#include <stdlib.h>
#include <fstream>
#include <vector>
#include "FreeImage.h"

int main()
{

    std::ifstream stream("c:/output/15_init_image.bin", std::ios::in | std::ios::binary);
    std::vector<uint8_t> contents((std::istreambuf_iterator<char>(stream)), std::istreambuf_iterator<char>());

    int width = 2048; // get the width of the image ;
    int height = 3096; // get the height of the image ;
    int bpp = 32;
    FreeImage_Initialise();
    int pitch = 512;

    FIBITMAP* src = FreeImage_ConvertFromRawBitsEx(true, contents.data(), FIT_BITMAP, width, height, pitch, FI_RGBA_RED_MASK,
        FI_RGBA_GREEN_MASK, FI_RGBA_BLUE_MASK, FALSE);
    FreeImage_Save(FIF_JPEG, src, "viewport.jpeg");

    
    return 0;

}
andre_lamothe
  • 2,171
  • 2
  • 41
  • 74

1 Answers1

1

From the comments:

Do you want the numeric value of the float64 stored in an int64, or do you want the bit pattern of the float stored as an int64?

the bit pattern actually

Getting the bit pattern with C++20:

    double d   = 1.0;
    
    uint64_t u = std::bit_cast<uint64_t>(d);
 
    u ^= 0x80'00'00'00'00'00'00'00; // toggle sign bit
    
    d = std::bit_cast<double>(u);

    std::cout << d; // prints -1

Getting the bit pattern without C++20:

double d = 0.1;

std::uint64_t u;

std::memcpy(&u, &d, sizeof d);

Once you have the bit pattern, you may also be interested in this post

SRNissen
  • 480
  • 9
  • I don't have access to c++20. Can you suggest another alternative ? What about If I want also the numeric float value to be represented in int64, Can you add a complete answer – andre_lamothe May 13 '23 at 20:58
  • What about the second sentence ? numeric float into int64 ? – andre_lamothe May 13 '23 at 21:19
  • If you know for certain that it fits in a 64 bit integer it's just `auto i = (int64_t)d;` and if you don't it's a bunch of checks and error handling. – SRNissen May 13 '23 at 21:51