Byte Array To Word Array


Recommended Posts

There are two ways I can think of off the top of my head.  One only works on the latest release of DAQFactory (because it uses hexstring):

 

to.word(from.hexstring(to.hexstring(x),2))

 

The trick here is that for to.word (or any of the others) requires a 2d array, where each row has all the bytes that make up the word, long, etc.  Fortunately, from.hexstring will take a hex string and convert it into a 2d array where the # of columns is the second parameter (though limited to 1, 2 and 4).  So, I simply convert to a hexstring, then convert back specifying 2 for a word, then use to.word to finally make the conversion.

 

The second way should work in all releases and is in a way, cooler (and probably faster):

 

filter(x + x[1,numrows(x)] * 256, (point(x)+1) % 2)

 

This assumes little endian unsigned word.  Given two bytes, to make an unsigned word, its x[0] + x[1] * 256.  Doing x + x[1,numrows(x)]*256 does the same thing for every element of x.  The only problem is that we only want every other result, because the odd results [1], [3], etc. contain the MSB of one word and the LSB of the next.  So, we use filter to throw away the wrong values.  Fortunately the expression that drives filter() doesn't have to be related to the thing being filtered.  In this case its a little related.  Point() returns an array where each element of the array is the index of the element.  So point(x) becomes simply {0,1,2,3 ...} up to the # of rows-1.  I add 1 because I want the even results ([0], [2],) then modulus 2 that to get an array that looks like this {1,0,1,0,1,0} etc.  Filter takes all the elements in the first expression that line up where the second expression is non-zero, thus picking every other element.

 

The only problem with the second method is that you can't convert to floats, but you could get around that by converting to a ulong, then doing to.float(from.ulong(...))

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.