I'm trying to build bit level addition for my emulator
It works for the most part, but the first bit of my accumulator register always gets set to 0, and I can't figure out why?
int main()
{
MCS6502 processor;
char mem1 = 0b00000001;
char mem2 = 0b00000001;
char mem3 = 0b00000000;
processor.LDA(mem1); //loads memory into accumulator
processor.ADC(mem2); //adds the inputed address to the accumulator
processor.STA(mem3); //stores the accumulator in memory
std::cout << +mem3 << std::endl;
return 0;
}
void MCS6502::LDA(const char &address)
{
registers[0] = address; //loads Accumulator
}
void MCS6502::STA(char &address)
{
address = registers[0]; //stores Accumulator
}
void MCS6502::ADC(const char &address)
{
char carry = 0b00000000;
if (flags[0] == true)
{
carry = 0b00000001;
}
char accumulator_bit_array[7];
char address_bit_array[7];
char result_bit_array[7];
ByteToBitArray(accumulator_bit_array, registers[0]);
std::cout << "accum bit after the function has ran " << +accumulator_bit_array[0] << std::endl;
ByteToBitArray(address_bit_array, address);
std::cout << "address bit after the function has ran " << +address_bit_array[0] << std::endl;
int i = 0;
while (i < 8)
{
std::cout << "counter "<< i << std::endl;
std::cout << "Accumulator bit in = " << +accumulator_bit_array[i] << std::endl;
std::cout << "Address bit in = " << +address_bit_array[i] << std::endl;
result_bit_array[i] = BitwiseAdd(accumulator_bit_array[i], address_bit_array[i], carry);
std::cout << "Bitwise Add restult = " << +result_bit_array[i] << std::endl;
i++;
}
registers[0] = BitArrayToByte(result_bit_array);
if (carry == 0b00000001)
{
flags[0] = true;
}
if (carry == 0b00000000)
{
flags[0] = false;
}
}
char BitwiseAdd(const char &bit1, const char &bit2, char &carry)
{
char xor_ = bit1 ^ bit2;
char ret = carry ^ xor_;
carry = (carry & xor_) | (bit1 & bit2);
return ret;
}
void ByteToBitArray(char bit_array[], const char &byte)
{
std::cout << "Byte inside array function before conversion " << +byte << std::endl;
bit_array[0] = byte & 0b00000001;
bit_array[1] = byte & 0b00000010;
bit_array[2] = byte & 0b00000100;
bit_array[3] = byte & 0b00001000;
bit_array[4] = byte & 0b00010000;
bit_array[5] = byte & 0b00100000;
bit_array[6] = byte & 0b01000000;
bit_array[7] = byte & 0b10000000;
bit_array[1] = bit_array[1] >> 1;
bit_array[2] = bit_array[2] >> 2;
bit_array[3] = bit_array[3] >> 3;
bit_array[4] = bit_array[4] >> 4;
bit_array[5] = bit_array[5] >> 5;
bit_array[6] = bit_array[6] >> 6;
bit_array[7] = bit_array[7] >> 7;
std::cout << "Bit inside array function after conversion " << +bit_array[0] << std::endl;
}
char BitArrayToByte(char bit_array[])
{
char byte = 0b00000000;
bit_array[1] = bit_array[1] << 1;
bit_array[2] = bit_array[2] << 2;
bit_array[3] = bit_array[3] << 3;
bit_array[4] = bit_array[4] << 4;
bit_array[5] = bit_array[5] << 5;
bit_array[6] = bit_array[6] << 6;
bit_array[7] = bit_array[7] << 7;
int i = 0;
while (i < 8)
{
byte = byte | bit_array[i];
i++;
}
return byte;
}
My output when I run this is:
Byte inside array function before conversion 1
Bit inside array function after conversion 1
accum bit after the function has ran 1
Byte inside array function before conversion 1
Bit inside array function after conversion 1
address bit after the function has ran 1
counter 0
Accumulator bit in = 0
Address bit in = 1
Bitwise Add restult = 1
counter 1
Accumulator bit in = 0
Address bit in = 0
Bitwise Add restult = 0
counter 2
Accumulator bit in = 0
Address bit in = 0
Bitwise Add restult = 0
counter 3
Accumulator bit in = 0
Address bit in = 0
Bitwise Add restult = 0
counter 4
Accumulator bit in = 0
Address bit in = 0
Bitwise Add restult = 0
counter 5
Accumulator bit in = 0
Address bit in = 0
Bitwise Add restult = 0
counter 6
Accumulator bit in = 0
Address bit in = 0
Bitwise Add restult = 0
counter 7
Accumulator bit in = 0
Address bit in = 0
Bitwise Add restult = 0
1
It should be 2, and I can't figure out why it doesn't work.
Your 3 arrays in ADC have 7 elements in them but the functions you pass them to expect 8. This results in undefined behavior, which is showing here as overwriting the first byte of the next array.
Related
Say I have a text file containing the 80bit hex number
0xabcdef0123456789abcd
My C++ program reads that using fstream into a char array called buffer.
But then I want to store it in a uint16_t array such that:
uint16_t * key = {0xabcd, 0xef01, 0x2345, 0x6789, 0xabcd}
I have tried several approaches, but I continue to get decimal integers, for instance:
const std::size_t strLength = strlen(buffer);
std::vector<uint16_t> arr16bit((strLength / 2) + 1);
for (std::size_t i = 0; i < strLength; ++i)
{
arr16bit[i / 2] <<= 8;
arr16bit[i / 2] |= buffer[i];
}
Yields:
arr16bit = {24930, 25444, 25958, 12337, 12851}
There must be an easy way to do this that I'm just not seeing.
Here is the full solution I came up with based on the comments:
int hex_char_to_int(char c) {
if (int(c) < 58) //numbers
return c - 48;
else if (int(c) < 91) //capital letters
return c - 65 + 10;
else if (int(c) < 123) //lower case letters
return c - 97 + 10;
}
uint16_t ints_to_int16(int i0, int i1, int i2, int i3) {
return (i3 * 16 * 16 * 16) + (i2 * 16 * 16) + (i1 * 16) + i0;
}
void readKey() {
const int bufferSize = 25;
char buffer[bufferSize] = { NULL };
ifstream* pStream = new ifstream("key.txt");
if (pStream->is_open() == true)
{
pStream->read(buffer, bufferSize);
}
cout << buffer << endl;
const size_t strLength = strlen(buffer);
int* hex_to_int = new int[strLength - 2];
for (int i = 2; i < strLength; i++) {
hex_to_int[i - 2] = hex_char_to_int(buffer[i]);
}
cout << endl;
uint16_t* key16 = new uint16_t[5];
int j = 0;
for (int i = 0; i < 5; i++) {
key16[i] = ints_to_int16(hex_to_int[j++], hex_to_int[j++], hex_to_int[j++], hex_to_int[j++]);
cout << "0x" << hex << key16[i] << " ";
}
cout << endl;
}
This outputs:
0xabcdef0123456789abcd
0xabcd 0xef01 0x2345 0x6789 0xabcd
I'm doing practice of bit manipulation in arduino with a 74HC595 shift register.
I would like to create an algorithm that allows the binary digit to perform this way:
1 0 0 0 0 0 0 1
0 1 0 0 0 0 1 0
0 0 1 0 0 1 0 0
.
.
.
1 0 0 0 0 0 0 1
In this type of function the decimal values are: (129,66,36,24,24,36,66,129) and so on in a loop.
How can I perform this type of shifting? I don't have any fluency thinking this type of operation, I have only performed a circular shift with "an algorithm" like:
//my circular shift
myByte = myByte*128 + myByte/2
But I don't know how to perform the output that I showed.
How can I do this? Thanks
For example you can use the following approach
#include <iostream>
#include <iomanip>
#include <limits>
int main()
{
unsigned char b = 0b10000001;
int width = std::numeric_limits<unsigned char>::digits / 2;
for ( int i = 0; i < width; i++ )
{
std::cout << std::hex << static_cast<int>( b ) << " - "
<< std::dec << static_cast<int>( b ) << '\n';
b = ( b & ( 0b1111 << width ) ) >> 1 | ( b & 0b1111 ) << 1;
}
for ( int i = 0; i < width; i++ )
{
std::cout << std::hex << static_cast<int>( b ) << " - "
<< std::dec << static_cast<int>( b ) << '\n';
b = ( b & ( 0b1111 << width ) ) << 1 | ( b & 0b1111 ) >> 1;
}
return 0;
}
The program output is
81 - 129
42 - 66
24 - 36
18 - 24
18 - 24
24 - 36
42 - 66
81 - 129
You're looking for a single operation that can be applied to an 8 bit number and result in the given pattern.
You want
x_(n+1) = f(x_(n))
for all given inputs and outputs. The problem is that there are a few potential inputs that have one of two possible outputs. You want both
36 = f(66)
and
129 = f(66)
This can't be done using only one variable. You can either implement a lookup table for the sequence you want (which is what I suggest). Or you can take two variables, implement circular shifts (in opposite directions) on each, and take the bitwise OR of the results.
uint8_t n1 = 128, n2 = 1;
for(;;)
{
std::cout << n1 | n2 << "\n";
n1 = circular_right_shift(n1);
n2 = circular_left_shift(n2);
}
Noticing that:
129,66,36,24,24,36,66,129 = 128+1; 64+2 ; 32+4; 16+8; 16+8; 32+4; 64+2; 128+1;
I ended up with this code:
int latchPin = 11;
int clockPin = 9;
int dataPin = 12;
int dt = 2000;
uint8_t n1 = 128, n2 = 1;
byte myByte = 0b10000001; //in BIN
void setup() {
Serial.begin(9600);
pinMode(latchPin,OUTPUT);
pinMode(dataPin,OUTPUT);
pinMode(clockPin,OUTPUT);
}
//circular shift to the left
void loop() {
digitalWrite(latchPin,LOW);
shiftOut(dataPin,clockPin,LSBFIRST,myByte);
digitalWrite(latchPin,HIGH);
int i;
myByte = 0b10000001; //restarting the value of 129
Serial.print("BIN: ");
Serial.print(myByte,BIN);
Serial.print(" --> ");
Serial.print("HEX: ");
Serial.print(myByte,HEX);
Serial.print(" --> ");
Serial.print("DEC: ");
Serial.println(myByte,DEC);
delay(200);
for (int i = 0; i < 7; i++) {
Serial.print("i: ");
Serial.println(i);
//int i1 = i+1;
//int myGap = myByte - (pow(2,i)); //no need to round when it's raised to 0;
//int firstpart = (myGap/2);
//int secondpart = 0.5 + pow(2,i1); //because it rounds the number. (i.e --> 1.9999 = 1)
//myByte = firstpart+ secondpart;
myByte = (myByte - (pow(2,i)))/2 + (0.5 + pow(2,i+1));
//Serial.print("firstpart: ");
//Serial.println(firstpart);
//Serial.print("secondpart: ");
//Serial.println(secondpart);
//delay(3000);
Serial.print("BIN: ");
Serial.print(myByte,BIN);
Serial.print(" --> ");
Serial.print("HEX: ");
Serial.print(myByte,HEX);
Serial.print(" --> ");
Serial.print("DEC: ");
Serial.println(myByte,DEC);
digitalWrite(latchPin,LOW);
shiftOut(dataPin,clockPin,LSBFIRST,myByte);
digitalWrite(latchPin,HIGH);
delay(100);
}
//myByte = myByte*2; //shift by right //using MSBFIRTS
//delay(dt);
}
And it works.
I'm trying to write a small program that can read and write 12 bit. The Input shouldn't have any issues but I'll include it so you understand the problem better. The input should be created as sample.lzw by the OFStream12Bits.cpp/main.cpp included below and the output should be reading the sample.lzw back from the write functions. I'm having problems with the output and getting code mismatch in the main when reading the code. I think the issues is from the operator>> and the readBit functions not sure exactly though.
Thank you very much for any help, I've been stuck on this for awhile!
The instructions for the readbit are as follows...
//basic readBit
//read12Bits(): 12Bit =
//declare Result : 12Bit = 0;
//for i = 1 to 12
//do
//declare lBit : Bit = get bit from input
//if(lBit == 1)
//then Result = (1 << (i-1)) + Result; //set bit at index i
//od
//return result
The part I don't understand is I need to return *this but there is no + operator so I can't use result to set the bit at index i. at the moment I have the code like this.
IFStream12Bits& IFStream12Bits::operator>>(int& a12BitValue)
{
//int Result = a12BitValue;
//a12BitValue = ((a12BitValue & 0x0fff) << 1);
a12BitValue = a12BitValue & 0x0fff;
for (int i = 0; i < 12; i++)
{
int bit = readBit();
if (bit == 1)
{
a12BitValue = (1 << (i - 1)) + a12BitValue; //set bit at index i
}
}
return *this;
}
Also The instructions for the readBit are as follows...
//implements mapping process. returns 0 or 1 depending on value of fBuffer[fByteIndex] & (1 << (fBitIndex - 1))
//see how it works with experiments
//at start check if (fByteCount == 0){reload();} then use reload() called as buffer does not contain any data before calling reload
//next fetch the bit store and then advance fByteIndex and fBitIndex
//if fBitIndex(highest to lowest) reaches 0 you need to switch to the next byte in the buffer. and also decrment fByteCount
//then finally return result
And the code is
int IFStream12Bits::readBit()
{
if (fByteCount == 0){ reload(); }
//int bit = fBuffer[fByteIndex] & (1 << (fBitIndex - 1));
int bit = fBuffer[fByteIndex] & (1 << (fBitIndex - 1));
int result = 0;
cout << "bit: " << bit << endl;
//added this just cause
if (bit == 0)
{
result = 0;
}
else
{
result = 1;
}
//additional logic required?
fByteIndex++;
fBitIndex--;
//switch to next byte in the buffer
if (fBitIndex == 0)
{
fByteCount--;
fBitIndex = 8;
fByteIndex = 0;
}
return result;
}
Here are the full .cpp files if you need to understand what is happening...
IFStream12Bits.cpp
#include "IFStream12Bits.h"
#include <iostream>
using namespace std;
//default constructor
IFStream12Bits::IFStream12Bits()
{
init();
}
//takes aFIleName
IFStream12Bits::IFStream12Bits(const char* aFileName)
{
init();
open(aFileName);
}
//deconstructor
IFStream12Bits::~IFStream12Bits()
{
close();
}
//initialize the integer member variables with sensible values
//:fBuffer(), fByteCount(0), fByteIndex(0), fBitIndex(8)
//fBitIndex(highToLow)
void IFStream12Bits::init()
{
for (int i = 0; i < 32; i++)
{
fBuffer[i] = 0;
}
fByteCount = 0;
fByteIndex = 0;
fBitIndex = 8;
}
//fills input buffer fBuffer with the next 32 bytes and sets fByteCount to number of bytes read
void IFStream12Bits::reload()
{
//fills fBuffer with 32 bytes
fIStream.read((char*)fBuffer, 32);
//fIStream.read((char*)fBuffer, fByteIndex + (fBitIndex % 8 ? 1 : 0));
//sets fByteCount to number of bytes read
fByteCount = fIStream.gcount();
}
//implements mapping process. returns 0 or 1 depending on value of fBuffer[fByteIndex] & (1 << (fBitIndex - 1))
//see how it works with experiments
//at start check if (fByteCount == 0){reload();} then use reload() called as buffer does not contain any data before calling reload
//next fetch the bit store and then advance fByteIndex and fBitIndex
//if fBitIndex(highest to lowest) reaches 0 you need to switch to the next byte in the buffer. and also decrment fByteCount
//then finally return result
int IFStream12Bits::readBit()
{
if (fByteCount == 0){ reload(); }
//int bit = fBuffer[fByteIndex] & (1 << (fBitIndex - 1));
int bit = fBuffer[fByteIndex] & (1 << (fBitIndex - 1));
int result = 0;
cout << "bit: " << bit << endl;
if (bit == 0)
{
result = 0;
}
else
{
result = 1;
}
//additional logic required?
fByteIndex++;
fBitIndex--;
//switch to next byte in the buffer
if (fBitIndex == 0)
{
fByteCount--;
fBitIndex = 8;
fByteIndex = 0;
}
return result;
}
void IFStream12Bits::open(const char* aFileName)
{
fIStream.open(aFileName, std::fstream::binary);
}
void IFStream12Bits::close()
{
fIStream.close();
}
bool IFStream12Bits::fail()
{
return fIStream.fail();
}
//true if no bytes left in input stream (fByteCount == 0)(should be zero if never read anythign from fIStream)
bool IFStream12Bits::eof()
{
return fByteCount == 0;
}
//read 12Bit codes from the bit input stream implements the read12Bits algorithm as shown in the tutorial
//basic readBit
//read12Bits(): 12Bit =
//declare Result : 12Bit = 0;
//for i = 1 to 12
//do
//declare lBit : Bit = get bit from input
//if(lBit == 1)
//then Result = (1 << (i-1)) + Result; //set bit at index i
//od
//return result
// multiply values by 2 to shift left???????????
IFStream12Bits& IFStream12Bits::operator>>(int& a12BitValue)
{
//int Result = a12BitValue;
//a12BitValue = ((a12BitValue & 0x0fff) << 1);
a12BitValue = a12BitValue & 0x0fff;
for (int i = 0; i < 12; i++)
{
int bit = readBit();
if (bit == 1)
{
a12BitValue = (1 << (i - 1)) + a12BitValue; //set bit at index i
}
}
return *this;
}
OFStream12Bits.cpp
#include "OFStream12Bits.h"
OFStream12Bits::OFStream12Bits()
{
init();
}
OFStream12Bits::OFStream12Bits(const char* aFileName)
{
init();
open(aFileName);
}
OFStream12Bits::~OFStream12Bits()
{
close();
}
void OFStream12Bits::init()
{
for (int i = 0; i < 32; i++)
{
fBuffer[i] = 0;
}
fByteIndex = 0;
fBitIndex = 8;
}
void OFStream12Bits::writeBit0()
{
fBitIndex--;
finishWriteBit();
}
void OFStream12Bits::writeBit1()
{
fBuffer[fByteIndex] += 1 << (fBitIndex - 1);
fBitIndex--;
finishWriteBit();
}
void OFStream12Bits::finishWriteBit()
{
if (fBitIndex == 0)
{
if (fByteIndex == 31)
{
fByteIndex++;
//write full buffer to stream
flush();
}
else
{
fByteIndex++;
fBitIndex = 8;
}
}
}
void OFStream12Bits::open(const char* aFileName)
{
fOStream.open(aFileName, std::ofstream::binary);
}
bool OFStream12Bits::fail()
{
return fOStream.fail();
}
void OFStream12Bits::close()
{
flush();
fOStream.close();
}
void OFStream12Bits::flush()
{
// do we need to add last byte?
fOStream.write((char*)fBuffer, fByteIndex + (fBitIndex % 8 ? 1 : 0));
init();
}
OFStream12Bits& OFStream12Bits::operator<<(int a12BitValue)
{
a12BitValue = a12BitValue & 0x0fff; // mask 12 lower bits
for (int i = 0; i < 12; i++) //write 12 bits
{
if (a12BitValue & 0x01) // the current lowest bit is set
{
writeBit1();
}
else
{
writeBit0();
}
a12BitValue >>= 1; // code = code / 2 --shifting value accross
}
return *this;
}
main.cpp
#include "OFStream12Bits.h"
#include "IFStream12Bits.h"
#include <iostream>
using namespace std;
void write4096()
{
cout << "Write 4096 codes" << endl;
OFStream12Bits lWriter("sample.lzw");
if (lWriter.fail())
{
cerr << "Error: unable to open output file" << endl;
exit(1);
}
for (int i = 4096; i >= 0; i--)
{
lWriter << i;
}
}
void read4096()
{
cout << "Read 4096 codes" << endl;
IFStream12Bits lInput("sample.lzw");
if (lInput.fail())
{
cerr << "Error: unable to open input file!" << endl;
exit(2);
}
for (int i = 4095; i >= 0; i--)
{
int l12BitValue;
lInput >> l12BitValue;
if (l12BitValue != i)
{
cerr << "Error: Code mismatch: " << l12BitValue << " != " << i << endl;
exit(3);
}
}
if (!lInput.eof())
{
cerr << "Error: Input stream not exhausted" << endl;
}
}
int main()
{
write4096();
read4096();
cout << "SUCCESS" << endl;
return 0;
}
Your input code is starting with the previous value. You should start with 0, because you're not clearing bits that aren't set.
IFStream12Bits& IFStream12Bits::operator>>(int& a12BitValue)
{
a12BitValue = 0;
for (int i = 0; i < 12; i++)
{
int bit = readBit();
if (bit == 1)
{
a12BitValue = (1 << (i - 1)) + a12BitValue; //set bit at index i
}
}
return *this;
}
Also, + will work here, but it's clearer to use bitwise operations when dealing with bits. Additionally, I think your shift is off. I would write the set bit line like this:
a12BitValue |= 1 << i;
If you think about it, when i is 0, you want to set the first bit (which is 1 or 1 << 0.) When i is 1, you want the next bit, and so on. So you should not need to subtract one.
I'm not sure that's the only problem, but you might try testing each class independently with unit tests. For example, start with a raw byte buffer, like {0x89, 0xAB, 0xCD, 0xEF, 0x01}, and then read three sets of 12 bits off. Verify they are correct. Then create an empty buffer, and write specific bits to it, and check that the bytes are correct.
By testing the algorithms independently, and with very strict input/output, you'll find it much easier to determine the flaw.
I have this program (c++) that calculates two variables values in a while cycle. I'm trying to wrote these values in a text file. Now I want to write the 5 values of my lforce variable in one line of the text file and the 5 values of my rforce variable in the other line.
How can I do that?
int i = 5;
int a2dVal = 0;
int a2dChannel = 0;
unsigned char data[3];
float g = 9.8;
int fsensor1;
int fsensor2;
int fsensor3;
int fsensor4;
int fsensor5;
int fsensor6;
float vsensor;
int lforce;
int rforce;
float vref = 2.5;
float vin = 3.3;
ofstream myfile ("/var/www/html/Sensors/all.txt");
if (myfile.is_open())
{
while(i > 0)
{
data[0] = 1; // first byte transmitted -> start bit
data[1] = 0b1000000000 |( ((a2dChannel & 9) << 4)); // second byte transmitted -> (SGL/DIF = 1, D2=D1=D0=0)
data[2] = 0; // third byte transmitted....don't care
a2d.spiWriteRead(data, sizeof(data) );
a2dVal = 0;
a2dVal = (data[1]<< 10) & 0b110000000000; //merge data[1] & data[2] to get result
a2dVal |= (data[2] & 0x0f);
sleep(1);
vsensor = (vref*a2dVal)/1024;
fsensor1 = ((vsensor/0.1391)-0.0329)*g;
fsensor2 = ((vsensor/0.1298)+0.1321)*g;
fsensor3 = ((vsensor/0.1386)+0.0316)*g;
fsensor4 = ((vsensor/0.1537)-0.0524)*g;
fsensor5 = ((vsensor/0.1378)+0.0922)*g;
fsensor6 = ((vsensor/0.1083)-0.0096)*g;
lforce = fsensor4 + fsensor5 + fsensor6;
rforce = fsensor1 + fsensor2 + fsensor3;
cout << lforce << " ";
cout << rforce << " ";
i--;
}
myfile << lforce << " " << rforce << " "; // here I want to write the variables in different lines of the text file
}
myfile.close();
return 0;
}
If you want to do this by manipulating file's cursor, you may use fseek and rewind functions. But I think it's unreasonbly difficult and much easier will be create 2 arrays and do somethig like this:
lforce = fsensor4 + fsensor5 + fsensor6;
lforceArray[5-i] = lforce;
rforce = fsensor1 + fsensor2 + fsensor3;
rforceArray[5-i] = rforce;
And then just write these arrays into the file.
I'm trying to implement a function that writes double to binary file in little endian byte order.
So far I have class BinaryWriter implementation:
void BinaryWriter::open_file_stream( const String& path )
{
// open output stream
m_fstream.open( path.c_str(), std::ios_base::out | std::ios_base::binary);
m_fstream.imbue(std::locale::classic());
}
void BinaryWriter::write( int v )
{
char data[4];
data[0] = static_cast<char>(v & 0xFF);
data[1] = static_cast<char>((v >> 8) & 0xFF);
data[2] = static_cast<char>((v >> 16) & 0xFF);
data[3] = static_cast<char>((v >> 24) & 0xFF);
m_fstream.write(data, 4);
}
void BinaryWriter::write( double v )
{
// TBD
}
void BinaryWriter::write( int v ) was implemented using Sven answer to What is the correct way to output hex data to a file? post.
Not sure how to implement void BinaryWriter::write( double v ).
I tried naively follow void BinaryWriter::write( int v ) implementation but it didn't work. I guess I don't fully understand the implementation.
Thank you guys
You didn't write this, but I'm assuming the machine you're running on is BIG endian, otherwise writing a double is the same as writing an int, only it's 8 bytes.
const int __one__ = 1;
const bool isCpuLittleEndian = 1 == *(char*)(&__one__); // CPU endianness
const bool isFileLittleEndian = false; // output endianness - you choose :)
void BinaryWriter::write( double v )
{
if (isCpuLittleEndian ^ isFileLittleEndian) {
char data[8], *pDouble = (char*)(double*)(&v);
for (int i = 0; i < 8; ++i) {
data[i] = pDouble[7-i];
}
m_fstream.write(data, 8);
}
else
m_fstream.write((char*)(&v), 8);
}
But don't forget generally int is 4 octects and double is 8 octets.
Other problem is static_cast. See this example :
double d = 6.1;
char c = static_cast(d); //c == 6
Solution reinterpret value with pointer :
double d = 6.1;
char* c = reinterpret_cast<char*>(&d);
After, you can use write( Int_64 *v ), which is a extension from write( Int_t v ).
You can use this method with :
double d = 45612.9874
binary_writer.write64(reinterpret_cast<int_64*>(&d));
Don't forget size_of(double) depend of system.
A little program converting doubles to an IEEE little endian representation.
Besides the test in to_little_endian, it should work on any machine.
include <cmath>
#include <cstdint>
#include <cstring>
#include <iostream>
#include <limits>
#include <sstream>
#include <random>
bool to_little_endian(double value) {
enum { zero_exponent = 0x3ff };
uint8_t sgn = 0; // 1 bit
uint16_t exponent = 0; // 11 bits
uint64_t fraction = 0; // 52 bits
double d = value;
if(std::signbit(d)) {
sgn = 1;
d = -d;
}
if(std::isinf(d)) {
exponent = 0x7ff;
}
else if(std::isnan(d)) {
exponent = 0x7ff;
fraction = 0x8000000000000;
}
else if(d) {
int e;
double f = frexp(d, &e);
// A leading one is implicit.
// Hence one has has a zero fraction and the zero_exponent:
exponent = uint16_t(e + zero_exponent - 1);
unsigned bits = 0;
while(f) {
f *= 2;
fraction <<= 1;
if (1 <= f) {
fraction |= 1;
f -= 1;
}
++bits;
}
fraction = (fraction << (53 - bits)) & ((uint64_t(1) << 52) - 1);
}
// Little endian representation.
uint8_t data[sizeof(double)];
for(unsigned i = 0; i < 6; ++i) {
data[i] = fraction & 0xFF;
fraction >>= 8;
}
data[6] = (exponent << 4) | fraction;
data[7] = (sgn << 7) | (exponent >> 4);
// This test works on a little endian machine, only.
double result = *(double*) &data;
if(result == value || (std::isnan(result) && std::isnan(value))) return true;
else {
struct DoubleLittleEndian {
uint64_t fraction : 52;
uint64_t exp : 11;
uint64_t sgn : 1;
};
DoubleLittleEndian little_endian;
std::memcpy(&little_endian, &data, sizeof(double));
std::cout << std::hex
<< " Result: " << result << '\n'
<< "Fraction: " << little_endian.fraction << '\n'
<< " Exp: " << little_endian.exp << '\n'
<< " Sgn: " << little_endian.sgn << '\n'
<< std::endl;
std::memcpy(&little_endian, &value, sizeof(value));
std::cout << std::hex
<< " Value: " << value << '\n'
<< "Fraction: " << little_endian.fraction << '\n'
<< " Exp: " << little_endian.exp << '\n'
<< " Sgn: " << little_endian.sgn
<< std::endl;
return false;
}
}
int main()
{
to_little_endian(+1.0);
to_little_endian(+0.0);
to_little_endian(-0.0);
to_little_endian(+std::numeric_limits<double>::infinity());
to_little_endian(-std::numeric_limits<double>::infinity());
to_little_endian(std::numeric_limits<double>::quiet_NaN());
std::uniform_real_distribution<double> distribute(-100, +100);
std::default_random_engine random;
for (unsigned loop = 0; loop < 10000; ++loop) {
double value = distribute(random);
to_little_endian(value);
}
return 0;
}