Convert Basic Types to Binary

Problem

You need to convert basic data types to a binary representation, possibly before encrypting them or writing them to a stream.

Solution

Use the BitConverter.GetBytes method to convert integers, individual characters, and floating point numbers to binary. Use the System.IO.BinaryWriter class to convert decimals and strings, or if you need to combine the binary output of multiple values.

Discussion

The .NET Framework includes the built-in intelligence to convert most basic types into binary representation. If you need to convert an individual value into a byte array, you can use the overloaded GetBytes method of the BitConverter class. Here’s an example:

Dim MyInt As Integer = 100 Dim Bytes() As Byte Bytes = BitConverter.GetBytes(MyInt) ...

Get Microsoft® Visual Basic® .NET Programmer's Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.