转换SRTM数据时的负高度

时间:2015-12-04 16:31:38

标签: c++ c file binaryfiles

我想从NASA SRTM数据集(http://dds.cr.usgs.gov/srtm/version2_1/SRTM3/Eurasia/)获得某个纬度/经度对的高度。

作为首发,我希望从HGT文件中获得所有高度:

int totalPx = 1201; //3 degree
char buffer[2];
for (int i=0; i<totalPx; i++)
{
    for (int j=0; j<totalPx; j++)
    {
        int pos = (i * totalPx + j) * 2;

        m_openedFile.seek(pos); //m_openedFile is a Qt QFile
        m_openedFile.read(buffer, 2);
        short h = 0 | (buffer[0] << 8) | (buffer[1] << 0);
        if (h < 0)
            printf("%d", h);
    }
}

这似乎适用于某些坐标(例如,高度值看起来似乎合理),但也有许多负高度值。如何正确读取SRTM / HGT文件?

此致

2 个答案:

答案 0 :(得分:3)

char转换为int

时,请注意标记扩展
// char buffer[2];
unsigned char buffer[2];
short h = buffer[0] << 8 | buffer[1];

答案 1 :(得分:1)

我明白了:问题是签名的char而不是unsigned char导致错误的位移:

int totalPx = 1201; //3 degree
unsigned char buffer[2];
for (int i=0; i<totalPx; i++)
{
    for (int j=0; j<totalPx; j++)
    {
        int pos = (i * totalPx + j) * 2;

        m_openedFile.seek(pos); //m_openedFile is a Qt QFile
        m_openedFile.read(buffer, 2);
        short h = 0 | (buffer[0] << 8) | (buffer[1] << 0);
        if (h < 0)
            printf("%d", h);
    }
}