c# - Converting base64 value to number -


i receiving data regarding vehicle speeds. have no control on input format, need use data.

the data sent me base64 encoded values. apparently, data started out number in little endian format. currently, code this:

public int b64toint(string input){      byte[] output = convert.frombase64string(input);     array.reverse(output);     if (output.length == 1)     {         return (int)output[0];     }     else if (output.length == 2)     {         return (int)bitconverter.toint16(output, 0);     }     else     {         return bitconverter.toint32(output, 0);     } } 

this works values receive, not all. way, convert value mph, need divide 1150.78.

the following value works: aab6qg== converts 27.19720537374 mph.

the following value not work: aa09 apparently, length of output array 3 bytes , don't know how handle situation.

the error message is: "destination array not long enough copy items in collection. check array index , length."

you build number yourself, decoded bytes. is, rather bitconverter.toint16 or bitconverter.toint32, following. (note don't reverse array.)

byte[] output = convert.frombase64string(input); console.writeline(output.length); int rslt = 0; (int = 0; < output.length; ++i) {     rslt <<= 8;     rslt += output[i]; } console.writeline(rslt); console.writeline((double)rslt / 1150.78); 

given input string of "aab6qg==", produces 27.1972053737465. "aa09" produces 2.94495907123864.

what i'm doing here fitting 4 bytes 32-bit integer. <<= 8 means "shift left 8 bits". effect bytes shifted 1 position left each time through loop.

so, given array { 00, 00, 7a, 42 }, rslt starts @ 0. result stays @ 0 until 3rd byte. then:

rslt += output[2];  // rslt = 0x0000007a // next time through loop rslt <<= 8          // rslt = 0x00007a00 rslt += output[3];  // rslt = 0x00007a42 

Comments

Popular posts from this blog

jquery - How can I dynamically add a browser tab? -

node.js - Getting the socket id,user id pair of a logged in user(s) -

keyboard - C++ GetAsyncKeyState alternative -