0

I do:

Dim BytArr() as Byte = BitConverter.GetBytes(1234)

Since, by default, they are 32 bits, it returns 4 byte elements.

I want to be able to control it to return only like two bytes. Maybe only three bytes. Are there any built-in functions to control it?

I don't want to rely on using shifting >> 8 >> 16 >> 24 >> 32, etc..

I also don't want to rely on type casting the data in GetBytes() to a specific datatype.

4

1 回答 1

2

It is not that GetBytes defaults to 32 bits, it is that GetBytes returns an array of the size required to hold the data type. If you pass a Long then you will get a 8 elements in your array.

The best way to control this is indeed casting the data you pass in. Otherwise you could truncate some of the number.

That being said, you could do something like this:

Dim BytArr() as Byte = Array.Resize(BitConverter.GetBytes(1234), 2)

But if the value you passed in exceeded what could be stored in 2 bytes (in this case) then you will have some very broken code.

于 2012-09-10T12:56:24.007 回答