i trying write generic method converts type of array byte array.
method definition: public byte[] convert_item_to_bytes(dynamic items) { byte[] bytearr = ?? //i tried blockcopy, not getting correct number of elements //buffer.blockcopy(items, 0, bytearr, 0, items.length ); return bytearr; } examples of method calls: convert_item_to_bytes(new int16[]{0x1234, 0x4567, 0x9574}); convert_item_to_bytes(new int32[]{0x3545, 0x3352, 0x9642, 0x5421}); convert_item_to_bytes(new uint64[]{0x4254, 0x8468}); //etc.... method calls can of float type.
i using dynamic in definition because know type online @ runtime.
ps: saw example uses binaryformatter , memorystream. not want use that. (how convert byte array type)
is there other possible way solve this?
there's quite issues you're asking, if don't want write code per type. luckily there aren't many numeric type in bcl, write out once or let generated.
a naive approach shown below:
public static void main() { int[] intarray = new int[] { 1, 2, 42, }; byte[] intoutput = converttobytearray(intarray, sizeof(int)); (int = 0; < intoutput.length; i++) { console.write("{0:x2} ", intoutput[i]); if ((i + 1) % singleitemsize == 0) { console.writeline(); } } } private static byte[] converttobytearray<t>(t[] input, int singleitemsize) t : struct, icomparable, icomparable<t>, iconvertible, iequatable<t>, iformattable { var outputarray = new byte[input.length * singleitemsize]; // iterate on input array, bytes each value , append them output array. (int = 0; < input.length; i++) { var thisitembytes = getbytes(input[i]); buffer.blockcopy(thisitembytes, 0, outputarray, * singleitemsize, singleitemsize); } return outputarray; } private static byte[] getbytes<t>(t input) t : struct, icomparable, icomparable<t>, iconvertible, iequatable<t>, iformattable { if (typeof(t) == typeof(int)) { return bitconverter.getbytes(convert.toint32(input)); } else if (typeof(t) == typeof(float)) { return bitconverter.getbytes(convert.tosingle(input)); } else { throw new argumentexception("t"); } }
this outputs following (depending on system's endianness):
01 00 00 00 02 00 00 00 2a 00 00 00
and converttobytearray()
method delivers useless array of 12 bytes given input of int[] { 1, 2, 42 }
. useless because don't know whether array contains 12 bytes, 6 chars, 3 ints, 3 floats or 3 unsigned integers.
apart that, there's lot of (performance) problems shown code, i'm sure can simplified.
instead perhaps can find solution seemingly xy problem.
Comments
Post a Comment