开发者

How to detect a non zero value in a binary file?

开发者 https://www.devze.com 2023-03-23 13:40 出处:网络
I have a problem which has been torturing for many hours. I need to be able to find the first non-zero value in an array (taking into account that there might be zeroes afterwards).

I have a problem which has been torturing for many hours. I need to be able to find the first non-zero value in an array (taking into account that there might be zeroes afterwards).

So if:

A [0, 0, 0, 0, 0, 0, 0, 0, 0, 16, 48, 24, 0, 0, 18, 9, 9, 7, 8, 0];

How do I set a variable say, int origin; equal to 9, such that A [origin] = 16?

My actual problem is more complex than this but that's essentially a simplified version of what's got me stuck. I'm actually working with a bluetooth device that outputs sectors of 512 bytes, however each byte in that sector represents different things. So I have made a for loop to extract byte number 224 which is the one i'm interested in, then I made an array of the value 224 for each sector. Although all the other bytes in the sector contain data, this particular byte doesn't start transmitting until much later. Since I want to analyse the data I need to know in which sector it starts being useful. Hence, I have the question above. All this information is completely irrelevant to the question but i've provided it for background.

Furthermore, and if you really want to top yourself with an answer, i need to output the byte number 224 as "latitude", byte number 225 as "longuitude" and byte 226 as "elevation" (for a GPS) as an xml format. Any ideas as to how i would output my three byte arrays to xml format? I have read they must be in string form first but that's easy:

string [] Lat = new string [Sectors];
for (int i = 0, i < sectors; i++)
{
   Lat[i] = A[i].ToString();
}

In the end, I'd like this as a result.

<document>
    <point lat = 开发者_高级运维"50.0" lon = "-60.5" ele = "605">
        <time> 16:54:08 </time>
    </point>
    <point .... etc
</document>

I hope I gave you enough information and I'd be helpful for ANY kind of help. cheers everyone! By the way, all the code should be in c# and I use visual c# 2010 express.


You state "array" in the question, which makes it easier:

int index = -1;    
for(int i = 0 ; i < arr.Length ; i++)
{
    if(arr[i] != 0)
    {
        index = i;
        break;
    }
}

Now if index is non-negative it is the index of the first non-zero. The value is then arr[index].

If you need to read from a FileStream just loop over Read and repeat. There is a hack with unsafe code you can use to make it marginally faster if you need.

0

精彩评论

暂无评论...
验证码 换一张
取 消