summaryrefslogtreecommitdiffstats
path: root/librns510.c
blob: 24c848f5771653a189351eefd56c0c1ff3cdb043 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
#include <stdio.h>

#ifdef  _MSC_VER 
#include "stdint.h"
#include "inttypes.h"
#else
#include <stdint.h>
#include <inttypes.h>
#include <strings.h>
#endif

#include <string.h>
#include <stdlib.h>

#if 0 /*3rd party calibration */
#define POI_CA 0x80000034       /*0 */
#define POI_CB 0xF1C71CD4       /*160 */

#define ZERO (POI_CA)
#define SCALE (((double) (POI_CB-POI_CA))/160.)
#endif

#if 0 /*From VW */

#define POI_CA 0x80b60b60 /*1*/
#define POI_CB 0xff49f49f /*179*/

#define SCALE (((double) (POI_CB-POI_CA))/178.)
#define ONE (POI_CA)
#define ZERO (ONE - (uint32_t) (SCALE+.5))

#endif

#if 1 /*From James*/
#define ZERO 0x80000000
#define SCALE (((float) 0x7FFFFFFF)/180.)
#endif



static void
fromz (int64_t a, double *lat, double *lon)
{
  uint64_t b, c;
  uint32_t d, e, f;

  memcpy (&b, &a, sizeof (a));
  e = f = 0;

  for (c = 1, d = 1; c; c <<= 1, d <<= 1)
    {
      if (b & c)
        e |= d;
      c <<= 1;
      if (b & c)
        f |= d;
    }

  *lon = e;
  *lat = f;

  *lon -= ZERO;
  *lat -= ZERO;

  *lon /= SCALE;
  *lat /= SCALE;

}

static void
toz (double lat, double lon, int64_t * a)
{
  uint64_t b, c;
  uint32_t d, e, f;

  lon *= SCALE;
  lat *= SCALE;
  lon += ZERO;
  lat += ZERO;

  e = (uint32_t) (lon + .5);
  f = (uint32_t) (lat + .5);

  //printf("%.1f %x\n",lat-ZERO, e,f);

  b = 0;
  for (c = 1, d = 1; c; c <<= 1, d <<= 1)
    {
      if (e & d)
        b |= c;
      c <<= 1;
      if (f & d)
        b |= c;
    }


  memcpy (a, &b, sizeof (*a));
}

void
librns510_encode (const char *slat, const char *slon, char *out)
{
  double lat = atof (slat), lon = atof (slon);
  int64_t z;

  toz (lat, lon, &z);

  sprintf (out, "%" PRId64, z);
}

void
librns510_decode (const char *code, char *slat, char *slon)
{
  double lat, lon;
  int64_t z;

#ifdef _MSC_VER
  sscanf(code, "%" PRId64, &z);
#else
  z = atoll (code);
#endif

  fromz (z, &lat, &lon);

  sprintf (slat, "%.10f", lat);
  sprintf (slon, "%.10f", lon);

}