Weird pointer dereferencing phenomenon

Hey guys,
I've got a decode function which decodes from a buffer. It reads the buffer to a var, _int64 myValue. Since the buffer stores a pointed double value, here's how I extract the original encoded val after the decoding itself is finished:

void* valuePointer = &myValue;
double finalVal = *(double*)valuePointer;

When i try something like: printf("final val = %f",finalVal), I get 0.0000 (which is wrong)

However when I try printf("myValue = %i, finalValue = %i",myValue,finalValue); i get 1083399168 and 1239.0 (which is right.)

It seems that finalValue only prints out correctly when it is preceded in a printf statement by myValue, as shown.

I really need to extract finalValue alone, does anyone know what is going on here and how to solve it?

thanks,

doct
Last edited on
Assuming that you don't have endian or fp-format issues, you can do a simple cast:
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;

int main()
  {
  // IEEE double precision value == -2 (little-endian format)
  unsigned char s[ 8 ] = { 0x00, 0x00,  0x00, 0x00,  0x00, 0x00,  0x00, 0xC0 };
  double d = *(double*)( s );
  cout << "-2 == " << d << endl;
  return 0;
  }

Also, please be careful how you cast pointers around. For example, you say:
printf("... finalValue = %i", ..., finalValue );
The types don't match, and could easily smash your stack.

Hope this helps.
For some reason, it only prints correctly when in tandem with myval, and it doesn't even store the correct value.

Right sorry, I meant to write %f haha.

Thannks for the reply, I'm not sure if this helps me though. Let me try to explain more clearly what I'm doing:

encoding:
1
2
3
4
5
6
7
8
9
10
double value = 4556.00;
_int64* myValue = (_int64*)&value;
unsigned char* pLoc = (unsigned char*)myValue;
unsigned char* buf = (unsigned char*)buffer; //buffer has been passed to 
//this function as a void pointer

//in a for loop:
   buf[i] = pLoc[i];

//therefor you have buf = {40,B1,CC,00,00,00,00,00} (hexadecimal) 


decoding:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
_int64 myval = 0;

//then in decode, buffer is passed again, and through some byte-masking 
//you get this:

myval = 40B1CC0000000000; // (hexadecimal)

//so then of course i try:

void* vp = (void*)&myval;
value = *(double*)vp;

printf("myval = %i, value = %f\n",myval,value);
//from the above printf, i get some random int for myval and 4556.0 for value
//but then if i do this just below:
printf("val = %f\n",value);
//i get value = 0.000 


what's goin on here??

Last edited on
Topic archived. No new replies allowed.