Naive implementation with memcpy()
, as per @Daniel Fischer's comment:
#include <stdio.h>
#include <string.h>
#include <limits.h>
void double_to_bits(double val);
int main(void)
{
unsigned idx;
double vals[] = { -1.0, 0.0, 1.0, 2.0 };
for (idx = 0; idx < 4; idx++ ) {
printf("\nvals[%u]= %+lf-->>", idx, vals[idx] );
double_to_bits(vals[idx] );
}
printf("\n");
return 0;
}
void double_to_bits(double val)
{
unsigned idx;
unsigned char arr[sizeof val];
memcpy (arr, &val, sizeof val);
for (idx=CHAR_BIT * sizeof val; idx-- ; ) {
putc(
( arr[idx/CHAR_BIT] & (1u << (idx%CHAR_BIT) ) )
? '1'
: '0'
, stdout
);
}
}
, and the same with a pointer (omitting the char array and the memcpy)
void double_to_bits2(double val)
{
unsigned idx;
unsigned char *ptr = (unsigned char*) &val;
for (idx=CHAR_BIT * sizeof val; idx-- ; ) {
putc(
( ptr[idx/CHAR_BIT] & (1u << (idx%CHAR_BIT) ) )
? '1'
: '0'
, stdout
);
}
}