Showing posts with label convert. Show all posts
Showing posts with label convert. Show all posts

Monday, July 28, 2008

Convert NMEA latitude & longitude to decimal

Here's how you convert latitude & longitude obtained from NMEA's GPGGA to decimal:











 NMEADecimal
latitude0302.7846903 + (02.78469/60) = 3.046412
longitude10141.82531101 + 41.82531/60) = 101.6971


Notice that for latitude of 0302.78469,


03 ==> degress. counted as is


02.78469 ==> minutes. divide by 60 before adding to degrees above


Hence, the decimal equivalent is:


03 + (02.78469/60) = 3.046412

Friday, May 30, 2008

Convert byte array to integer in Java

The following JUnit test shows how to convert a byte array into a single integer in Java.


import static org.junit.Assert.*;
import org.junit.Test;

public class BaitTest {

@Test
public void printInt() {
byte[] bs = {
(byte)0x00,
(byte)0x00,
(byte)0x00,
(byte)0x16,
(byte)0x04
};

int address = (bs[0] << 32) | (bs[1] << 24) |
(bs[2] << 16) | (bs[3] << 8) | bs[4];

System.out.println("address (int) = [" + address + "]");
System.out.printf("address (hex) = [%X]\n", address);

assertTrue(5636 == address);
}
}


In the above, the line :

int address = (bs[0] << 32) | (bs[1] << 24) |
(bs[2] << 16) | (bs[3] << 8) | bs[4];

is where we convert the byte array to a single integer using the assumption that the most significant byte (i.e. MSB) is at index 0. Note that the bit shift values are incremented by multiples of 8 i.e. or 8*0, 8*1, 8*2, 8*3 and 8*4.

In Java 5 upwards, to print a decimal number as hexadecimal, use the "%X" modifier in "printf", as shown in this line from the above code :

System.out.printf("address (hex) = [%X]\n", address);


You'll see that the above will print out "1604" (i.e. 00 00 00 16 04) which is what the byte array looks like at the top of the code, i.e. :


byte[] bs = {
(byte)0x00,
(byte)0x00,
(byte)0x00,
(byte)0x16,
(byte)0x04
};