How do I limit BitConverter.GetBytes() to return only a certain amount of bytes using VB.NET?

StackOverflow https://stackoverflow.com/questions/12345111

  •  01-07-2021
  •  | 
  •  

Question

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.

Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top