Fabricio Rodriguez
Fabricio Rodriguez

Reputation: 4239

Latitude/Longitude coordinates to BCD in C#

I am writing C# code to program geo-fences on a GPS tracker (Sinowell G102). The geo-fences are rectangular. I basically have to take the top-left corner coordinate, and bottom-right corner coordinate, and program it into the tracker. Now, the tracker expects these coordinates in BCD format (Binary-Coded Decimal). Each coordinate being 4 bytes long. Now, I figured how to convert a positive latitude or longitude coordinate into BCD - according to the tracker's protocol manual, a coordinate such as:

22° 33.995′ (i.e. 22 degrees North, 33.995 minutes East)

becomes the four bytes 02 23 39 95

Which is pretty straight forward. My problem, however, is that I don't know how to tackle the negative coordinates of the Southern Hemisphere (such as -25° 33.995′, as we have here in South Africa)

I managed to get in touch with the manufacturers of this tracker, but unfortunately it's a Chinese firm, and their English is not very good. They did however send me the following image:

enter image description here

Unfortunately, I don't fully understand this code. I would greatly appreciate any help.... Thank you.

Upvotes: 1

Views: 620

Answers (1)

Nick
Nick

Reputation: 13414

if (val&0x80000000)

This if statement will be true if the high bit is set. 0x80000000 in binary is a 1 followed by all zeros.

val&0x7FFFFFFF

This statement will set the high bit to zero.

0-(val&0x7FFFFFFF)

This negates the value after setting the high bit to zero.

So, reversing this, you'll want to convert the absolute value (abs(raw)) to binary using your existing algorithm. Say the original value is in a variable called raw, and the binary is in a variable called binary. If raw is negative, you'll need to set the high bit on binary. Like this:

if (raw < 0) {
    binary = binary | 0x80000000;
}

& and | are bitwise operations. The apply and/or logic to each of the bits in the arguments. So 0x1&0x0 = 0, 0x1&0x1 = 1, 0x0|0x0 = 0x0, and 0x0|0x1 = 0x1.

Upvotes: 2

Related Questions