[VB]十进制/十六进制/二进制 间的转换

本文介绍了如何使用VB函数实现不同进制之间的转换,包括十进制到十六进制、十六进制到十进制以及十进制到二进制的转换方法,并提供了具体的代码示例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 

十进制/十六进制/二进制 间的转换


1,十进制转十六进制

Function Dec2Hex(value As StringAs String
    value 
= Trim$(value)
    
    
If Len(value) = 0 Then
        Dec2Hex 
= ""
    
Else
        Dec2Hex 
= Hex(value)
    
End If
    
    
If Len(Dec2Hex) = 1 Then
        Dec2Hex 
= "0" & Dec2Hex
    
ElseIf Len(Dec2Hex) <> 2 Then
        Dec2Hex 
= "ERR"
        
MsgBox ("変数の長さはただしくない")
    
End If

End Function

 

2,十六进制转十进制

Function Hex2Dec(value As StringAs Byte
    value 
= Trim$(value)
    
    
If Len(value) = 0 Then
        
MsgBox "error"
        
Exit Function
    
End If
    
    Hex2Dec 
= CByte("&H" & value)

End Function

 

2,十进制转二进制

以下VB函数可以完成十进制转换二进制的工作。另外,这个函数还加入了对二进制长度的判断,如果转换出来的二进制长度低于最小值,函数会自动在二进制字符串前补0。

Public Function DecimalToBinary(DecimalValue As Long, MinimumDigits As Integer)
As String

' Returns a string containing the binary
'
 representation of a positive integer.

Dim result As String
Dim ExtraDigitsNeeded As Integer

' Make sure value is not negative.
DecimalValue = Abs(DecimalValue)

' Construct the binary value.
Do
    result 
= CStr(DecimalValue Mod 2& result
    DecimalValue 
= DecimalValue  2
Loop While DecimalValue > 0

' Add leading zeros if needed.

ExtraDigitsNeeded 
= MinimumDigits - Len(result)
If ExtraDigitsNeeded > 0 Then
    result 
= String(ExtraDigitsNeeded, "0"& result
End If

DecimalToBinary 
= result

End Function 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值