如何将VB的Double转换为COBOL的COMP-3?

时间:2009-02-11 03:21:19

标签: vb.net cobol

有没有人知道如何将VB Double转换为Cobol S9(15)V99 Comp-3数据类型?

1 个答案:

答案 0 :(得分:5)

如果不需要在同一个程序中完成,在我看来,找到VB COBOL都能理解的通用格式会更容易。

那将是文字。换句话说,最简单的解决方案可能是将数字作为文本“3.14159”写入文件,并让COBOL代码以该格式读取,MOVE将其写入COMP-3字段?< / p>

如果不可能,COMP-3是一种相当简单的BCD类型。我会将数字转换为字符串,然后一次将两个字符转换为字节数组。

S9(15)V99需要18个nybbles(nybble是4位,或半个八位字节)来存储:

  • 整数位(十五个nybbles)。
  • 分数位(两个nybbles)。
  • 标志(一个nybble)。

小数点不需要空格,因为V是隐含的小数,而不是真实小数。

因此数字3.14将表示为字节:

00 00 00 00 00 00 00 31 4C

唯一棘手的问题是最终签署nybble(C表示正数,D表示否定数据。

这里有一些我在Excel VBA中编写的代码(遗憾的是我没有在这台机器上安装VB),它向您展示了如何操作。 makeComp3()函数应该很容易转换成真正的VB程序。

宏测试程序输出分别为04976的值00314C({ {1}}是00314C)。

第一步(在所有声明之后)是将双倍乘以10的相关幂,然后将其变为整数:

+3.14

接下来,我们将其设置为正确大小的字符串,以便于处理:

Option Explicit

' makeComp3. '
'   inp is the double to convert. '
'   sz is the minimum final size (with sign). '
'   frac is the number of fractional places. '

Function makeComp3(inp As Double, sz As Integer, frac As Integer) As String
    Dim inpshifted As Double
    Dim outstr As String
    Dim outbcd As String
    Dim i As Integer
    Dim outval As Integer
    Dim zero As Integer
    zero = Asc("0")

    ' Make implied decimal. '
    inpshifted = Abs(inp)
    While frac > 0
        inpshifted = inpshifted * 10
        frac = frac - 1
    Wend
    inpshifted = Int(inpshifted)

然后我们一次处理两个数字的字符串,并将每对数据组合成一个输出的nybble。最后一步是处理最后一位数字以及符号:

    ' Get as string and expand to correct size. '
    outstr = CStr(inpshifted)
    While Len(outstr) < sz - 1
        outstr = "0" & outstr
    Wend
    If Len(outstr) Mod 2 = 0 Then
        outstr = "0" & outstr
    End If

这只是测试工具,尽管可能还有一些测试用例: - )

    ' Process each nybble pair bar the last. '
    outbcd = ""
    For i = 1 To Len(outstr) - 2 Step 2
        outval = (Asc(Mid(outstr, i)) - zero) * 16
        outval = outval + Asc(Mid(outstr, i + 1)) - zero
        outbcd = outbcd & Chr(outval)
    Next i

    ' Process final nybble including the sign. '    
    outval = (Asc(Right(outstr, 1)) - zero) * 16 + 12
    If inp < 0 Then
        outval = outval + 1
    End If

    makeComp3 = outbcd & Chr(outval)
End Function