Convert number to hex in byte array (&H?? format)

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • SciCat
    New Member
    • Feb 2013
    • 2

    Convert number to hex in byte array (&H?? format)

    Hello!

    I'm running Visual Basic 2012

    I'm having a certain amount of sucess controlling my serial port but now I've hit a wall.

    Code:
     Public com3 As New SerialPort("COM3", 9600, Parity.None, 8, StopBits.One)
    
        Public Hexe As Integer = Hex(100)
    
          Public Sub New()
            InitializeComponent()
            For Each sp As String In My.Computer.Ports.SerialPortNames
                ListBox1.Items.Add(sp)
            Next
            If com3.IsOpen = False Then
                com3.Open()
            End If
    
                Dim Absolut() As Byte = {1, 4, 0, 0, 0, 0, 0, Int in Hex (&H format), Int in Hex + 5 (control bit)}
                com3.Write(Absolut, 0, Absolut.Length)
        End Sub
    As you can see I need either the whole byte in hex or just parts of it, problem is that Hex(Int) gives it as a string instead of the &H?? format I need. I can't find any solution on MSDN.

    Am I just not seeing the obvious?

    Best Regards
    SciCat

    EDIT: The code is incomplete, I didn't want to dump a 100+ line blob, the code works in its entirety.
    Last edited by SciCat; Feb 25 '13, 03:23 PM. Reason: Should mention that the code isn't complete. Added version info.
  • SciCat
    New Member
    • Feb 2013
    • 2

    #2
    I have managed to solve the conversion problem using Bitshift in the byte itself using an integer:

    Code:
    Public Class Form1
        Public com3 As New SerialPort("COM3", 9600, Parity.None, 8, StopBits.One)
    
        Public Sub SendCMD(Adress As Byte, Command As Byte, Type As Byte, Motor As Byte, Value As Integer)
            Dim TxBuffer() As Byte
            Dim i As Integer
    
            TxBuffer = {Adress, Command, Type, Motor, Value >> 24, Value >> 16, Value >> 8, Value & &HFF, 0}
            For i = 0 To 7
                TxBuffer(8) = TxBuffer(8) + TxBuffer(i)
            Next
            com3.Write(TxBuffer, 0, 9)
    
    
        End Sub
    
    
        Public Sub New()
            InitializeComponent()
            For Each sp As String In My.Computer.Ports.SerialPortNames
                ListBox1.Items.Add(sp)
            Next
            If com3.IsOpen = False Then
                com3.Open()
            End If
            SendCMD(1, 1, 0, 0, 1)
            Tid.Enabled = True
    
        End Sub
    
        Private Sub Tid_Tick(sender As Object, e As EventArgs) Handles Tid.Tick
            SendCMD(1, 3, 0, 0, 1)
        End Sub
    But when I run the code I get an arithmetic overflow, did i do something wrong?


    EDIT: Everything works! Keeping it here for future reference.
    Last edited by SciCat; Mar 2 '13, 05:22 PM. Reason: changed the for i = 0 to 8 to 7, Idiocy on my part

    Comment

    Working...