c# - byte[] to ushort[] -
here question. bear me giving little explanation:
i reading tiff image buffer; each pixel of tiff represented ushort (16 bits data, non-negtive).
my image size 64*64 = 4096. when tiff loaded buffer, buffer length hence 8192 (twice much 4096). guess because in buffer, computer uses 2 bytes store single pixel value.
i want value particular pixel, in case should combine every 2 bytes 1 ushort?
for example: 00000000 11111111 -> 0000000011111111?
here code:
public static void loadtiff(string filename, int pxlidx, ref int pxlvalue) { using (tiff image = tiff.open(filename, "r")) { if (image == null) return; fieldvalue[] value = image.getfield(tifftag.imagewidth); int width = value[0].toint(); byte[] buffer = new byte[image.stripsize()]; (int strip = 0; strip < image.numberofstrips(); strip++) image.readencodedstrip(strip, buffer, 0, -1); // conversion here: //ushort bufferhex = bitconverter.touint16(buffer, 0); image.close(); } }
how read byte[] buffer ensure can 16 bits ushort pixel value?
thanks
since each pixel represented 16 bits, may more convenient programming perspective represent byte[]
ushort[]
of half length, not required.
the best solution depends on how want consume buffer.
you define helper method
ushort getimagedataatlocation(int x, int y) { offset = y * height + x; homecoming bitconverter.touint16(buffer, offset); }
that uses input coordinates determine offset in original byte[]
, returns ushort
composed of appropriate bytes.
if tiff stores info big-endian , scheme little-endian, have reverse order of bytes prior conversion. 1 way is:
ushort getimagedataatlocation(int x, int y) { offset = y * height + x; // switch endianness e.g. tiff big-endian, host scheme little-endian ushort result = ((ushort)buffer[0]) << 8 + buffer[1]; homecoming result; }
if code might ever run on platforms different endianness (intel , amd both little-endian) can determine endianness @ runtime using
bitconverter.islittleendian
for details on bitconverter, see http://msdn.microsoft.com/en-us/library/system.bitconverter.touint16.aspx
c# bytebuffer data-conversion ushort
No comments:
Post a Comment