O'Reilly logo

Microsoft® Visual Basic® .NET Programmer's Cookbook by Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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) ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required