Visual Basic - Technik, FAQ, Tricks, Beispiele

Home / Allgemein / Bits / Bin

Ganz-Zahlen in Binärdarstellung

Impressum
Kontakt
DSVGO
Historie
28.04.2003Umkehrfunktion für Hex genannt
27.12.2000Erste Version

Motivation

Hexadezimal

VB kennt die Hex-Funktion, um eine Ganz-Zahl in seine hexadezimale Darstellung zu konvertieren. Die Umkehrfunktion dazu ist übrigens via CLng("&H" & s) erreichbar, falls s einen hexadezimalen Ausdruck (etwa "28D0F000") enthält.

Binar

Leider gibt es eine solche Funktion nicht für die binäre Darstellung. Daher präsentiere ich unten die Funktionen BinByte, BinInt und BinLng.

Beispiele

Der Ausdruck BinByte(7) gibt den String "00000111" zurück.

Der Ausdruck BinInt(-1) gibt dagegen den String "1111111111111111" zurück (negatives Vorzeichen).

Code / Quelltext

'Byte in Binär:
Public Function BinByte(ByVal Value As Byte) As String
  Dim i As Long
  
  BinByte = String$(8, "0")
  
  i = 15
  Do While Value
    If Value And 1 Then MidB$(BinByte, i) = "1"
    Value = Value \ 2
    i = i - 2
  Loop
End Function
'Integer in Binär:
Public Function BinInt(ByVal Value As Integer) As String
  Dim i As Long
  
  BinInt = String$(16, "0")
  If Value And &H8000 Then
    'negatives Vorzeichen beachten:
    MidB$(BinInt, 1) = "1"
    Value = Value Xor &H8000
  End If
  
  i = 31
  Do While Value
    If Value And 1 Then MidB$(BinInt, i) = "1"
    Value = Value \ 2
    i = i - 2
  Loop
End Function
'Long in Binär:
Public Function BinLng(ByVal Value As Long) As String
  Dim i As Long
  
  BinLng = String$(32, "0")
  If Value And &H80000000 Then
    'negatives Vorzeichen beachten:
    MidB$(BinLng, 1) = "1"
    Value = Value Xor &H80000000
  End If
  
  i = 63
  Do While Value
    If Value And 1 Then MidB$(BinLng, i) = "1"
    Value = Value \ 2
    i = i - 2
  Loop
End Function

© Jost Schwider, 27.12.2000-28.04.2003 - http://vb-tec.de/bits.htm