Pergunta

Eu tenho uma série de arquivos simples ASCII que vêm dentro de um mainframe a ser processado por um aplicativo C #. Uma nova alimentação foi introduzida com um campo embaladas Decimal (COMP-3), o qual necessita de ser convertida para um valor numérico.

Os arquivos estão sendo transferidos via FTP, usando o modo de transferência ASCII. Estou preocupado que o campo binário pode conter o que será interpretado como muito baixa códigos ASCII ou caracteres em vez de um valor de controle -. Ou pior, podem ser perdidos no processo de FTP

O que é mais, os campos estão sendo lidos como strings. Eu posso ter a flexibilidade de trabalhar em torno desta parte (stream ou seja, um de algum tipo), mas o negócio vai dar-me pushback.

A exigência leia "Converter de HEX para ASCII", mas claramente que não deu os valores corretos. Qualquer ajuda seria apreciada; ele não precisa ser específico do idioma, desde que você pode explicar a lógica do processo de conversão.

Foi útil?

Solução

Em primeiro lugar você deve eliminar o fim dos problemas de linha (EOL) de tradução que serão causados ??pelo modo de transferência ASCII. Você está absolutamente certo em estar preocupado com a corrupção de dados quando os valores BCD acontecer para corresponder aos caracteres EOL. O pior aspecto deste problema é que ele irá ocorrer raramente e inesperadamente.

A melhor solução é mudar o modo de transferência para BIN. Este é adequada uma vez que os dados que você está transferindo é binário. Se não for possível usar o modo de transferência FTP correto, você pode desfazer o dano modo ASCII no código. Tudo que você tem a fazer é convertido \ r \ n pares de volta para \ n. Se eu fosse você gostaria de ter certeza isso é bem testado.

Uma vez que você lidou com o problema EOL, a conversão COMP-3 é bastante straigtforward. Eu era capaz de encontrar este artigo no MS KnowledgeBASE com código de exemplo em BASIC. Veja abaixo uma porta VB.NET deste código.

Uma vez que você está lidando com valores COMP-3, o formato de arquivo que você está lendo quase certamente fixou tamanhos gravar com comprimentos de campo fixos. Se eu fosse você, eu iria chegar em minhas mãos de uma especificação de formato de arquivo antes de ir mais longe com isso. Você deve estar usando um BinaryReader ao trabalho com esses dados. Se alguém está empurrando para trás quanto a este ponto, gostaria de ir embora. Deixe-os encontrar alguém para entrar sua loucura.

Aqui está uma porta VB.NET do código de exemplo BASIC. Eu não testei isso, porque eu não tenho acesso a um arquivo COMP-3. Se isso não funciona, eu iria remeter para o código de exemplo MS originais para orientação, ou referências nas outras respostas para essa pergunta.

Imports Microsoft.VisualBasic

Module Module1

'Sample COMP-3 conversion code
'Adapted from http://support.microsoft.com/kb/65323
'This code has not been tested

Sub Main()

    Dim Digits%(15)       'Holds the digits for each number (max = 16).
    Dim Basiceqv#(1000)   'Holds the Basic equivalent of each COMP-3 number.

    'Added to make code compile
    Dim MyByte As Char, HighPower%, HighNibble%
    Dim LowNibble%, Digit%, E%, Decimal%, FileName$


    'Clear the screen, get the filename and the amount of decimal places
    'desired for each number, and open the file for sequential input:
    FileName$ = InputBox("Enter the COBOL data file name: ")
    Decimal% = InputBox("Enter the number of decimal places desired: ")

    FileOpen(1, FileName$, OpenMode.Binary)

    Do Until EOF(1)   'Loop until the end of the file is reached.
        Input(1, MyByte)
        If MyByte = Chr(0) Then     'Check if byte is 0 (ASC won't work on 0).
            Digits%(HighPower%) = 0       'Make next two digits 0. Increment
            Digits%(HighPower% + 1) = 0   'the high power to reflect the
            HighPower% = HighPower% + 2   'number of digits in the number
            'plus 1.
        Else
            HighNibble% = Asc(MyByte) \ 16      'Extract the high and low
            LowNibble% = Asc(MyByte) And &HF    'nibbles from the byte. The
            Digits%(HighPower%) = HighNibble%  'high nibble will always be a
            'digit.
            If LowNibble% <= 9 Then                   'If low nibble is a
                'digit, assign it and
                Digits%(HighPower% + 1) = LowNibble%   'increment the high
                HighPower% = HighPower% + 2            'power accordingly.
            Else
                HighPower% = HighPower% + 1 'Low nibble was not a digit but a
                Digit% = 0                  '+ or - signals end of number.

                'Start at the highest power of 10 for the number and multiply
                'each digit by the power of 10 place it occupies.
                For Power% = (HighPower% - 1) To 0 Step -1
                    Basiceqv#(E%) = Basiceqv#(E%) + (Digits%(Digit%) * (10 ^ Power%))
                    Digit% = Digit% + 1
                Next

                'If the sign read was negative, make the number negative.
                If LowNibble% = 13 Then
                    Basiceqv#(E%) = Basiceqv#(E%) - (2 * Basiceqv#(E%))
                End If

                'Give the number the desired amount of decimal places, print
                'the number, increment E% to point to the next number to be
                'converted, and reinitialize the highest power.
                Basiceqv#(E%) = Basiceqv#(E%) / (10 ^ Decimal%)
                Print(Basiceqv#(E%))
                E% = E% + 1
                HighPower% = 0
            End If
        End If
    Loop

    FileClose()   'Close the COBOL data file, and end.
End Sub

End Module

Outras dicas

Fui assistir os cargos em vários conselhos relativos converter Comp-3 dados BCD a partir de arquivos de mainframe "legado" a algo utilizável em C #. Em primeiro lugar, gostaria de dizer que eu sou menos do que apaixonado pelas respostas que algumas dessas mensagens recebidas - especialmente aqueles que disseram essencialmente, "por que você está nos incomodando com essas não-C # / C ++ posts relacionados", e também "se você precisa de uma resposta sobre algum tipo de convenção COBOL, por que você não ir visitar um site orientado COBOL". Isso, para mim, é BS completa como não vai ser uma necessidade para provavelmente muitos anos, (infelizmente), para desenvolvedores de software para entender como lidar com alguns destes problemas legados que existem no mundo real. Assim, mesmo se eu me bateu sobre este post para o seguinte código, eu vou compartilhar com vocês uma experiência do mundo real que eu tive que lidar com respeito conversão COMP-3 / EBCDIC (e sim, eu sou aquele que fala de " disquetes, papel-tape, pacotes de discos etc ... -. tenho sido um engenheiro de software desde 1979" )

Primeiro - entender que qualquer arquivo que você lê a partir de um sistema legado principal-frame como a IBM vai apresentar os dados para você em formato EBCDIC e, a fim de converter qualquer desses dados para uma cadeia de C # / C ++ você pode lidar com você vai ter que usar a tradução apropriada página de código para obter os dados em formato ASCII. Um bom exemplo de como lidar com isso seria:

StreamReader readFile = new StreamReader (caminho, Encoding.GetEncoding (037);. // 037 = EBCDIC para tradução ASCII

Isto irá assegurar que qualquer coisa que você ler a partir deste fluxo será então convertido em ASCII e pode ser usado em um formato string. Isto inclui "Zoned decimal" (Pic 9) e "Texto" (Pic X) campos declarado pelos COBOL. No entanto, isto não significa necessariamente converter comp-3 campos para o equivelant correcta "binário" quando lidas em um ou byte matriz de caracteres [] []. Para fazer isso, a única maneira que você está indo cada vez para obter este traduzido corretamente (mesmo usando UTF-8, UTF-16, padrão ou qualquer outro) páginas de código, você vai querer abrir o arquivo como este:

= FileStream fileStream novo FileStream (caminho, FIleMode.Open, FIleAccess.Read, FileShare.Read);

É claro, a opção "FileShare.Read" é ??"opcional".

Quando você tiver isolado o campo que você deseja converter em um valor decimal (e posteriormente a uma seqüência de caracteres ASCII, se necessário), você pode usar o código a seguir - e isso tem sido basicamente roubado da MicroSoft "UnpackDecimal" postagem que você pode obter em:

http: // www. microsoft.com/downloads/details.aspx?familyid=0e4bba52-cc52-4d89-8590-cda297ff7fbd&displaylang=en

isolei (eu acho) Quais são as mais importantes partes desta lógica e consolidou-lo em dois um método que você pode fazer com o que você quer. Para os meus propósitos, eu escolhi para deixar isso como retornar um valor decimal que eu poderia, então, fazer com que eu queria. Basicamente, o método é chamado de "desempacotar" e você passá-lo uma matriz byte [] (não mais que 12 bytes) e a escala como um int, que é o número de casas decimais que você deseja ter retornado no valor Decimal. Espero que isso funciona para você, assim como ele fez por mim.

    private Decimal Unpack(byte[] inp, int scale)
    {
        long lo = 0;
        long mid = 0;
        long hi = 0;
        bool isNegative;

        // this nybble stores only the sign, not a digit.  
        // "C" hex is positive, "D" hex is negative, and "F" hex is unsigned. 
        switch (nibble(inp, 0))
        {
            case 0x0D:
                isNegative = true;
                break;
            case 0x0F:
            case 0x0C:
                isNegative = false;
                break;
            default:
                throw new Exception("Bad sign nibble");
        }
        long intermediate;
        long carry;
        long digit;
        for (int j = inp.Length * 2 - 1; j > 0; j--)
        {
            // multiply by 10
            intermediate = lo * 10;
            lo = intermediate & 0xffffffff;
            carry = intermediate >> 32;
            intermediate = mid * 10 + carry;
            mid = intermediate & 0xffffffff;
            carry = intermediate >> 32;
            intermediate = hi * 10 + carry;
            hi = intermediate & 0xffffffff;
            carry = intermediate >> 32;
            // By limiting input length to 14, we ensure overflow will never occur

            digit = nibble(inp, j);
            if (digit > 9)
            {
                throw new Exception("Bad digit");
            }
            intermediate = lo + digit;
            lo = intermediate & 0xffffffff;
            carry = intermediate >> 32;
            if (carry > 0)
            {
                intermediate = mid + carry;
                mid = intermediate & 0xffffffff;
                carry = intermediate >> 32;
                if (carry > 0)
                {
                    intermediate = hi + carry;
                    hi = intermediate & 0xffffffff;
                    carry = intermediate >> 32;
                    // carry should never be non-zero. Back up with validation
                }
            }
        }
        return new Decimal((int)lo, (int)mid, (int)hi, isNegative, (byte)scale);
    }

    private int nibble(byte[] inp, int nibbleNo)
    {
        int b = inp[inp.Length - 1 - nibbleNo / 2];
        return (nibbleNo % 2 == 0) ? (b & 0x0000000F) : (b >> 4);
    }

Se você tiver alguma dúvida, publicá-las aqui - porque eu suspeito que eu estou indo para obter "inflamado" como toda a gente que optou por postar perguntas que são pertinentes para todays questões ...

Obrigado, John -. O Elder

Se os dados originais foi em EBCDIC seu campo COMP-3 foi truncado. O processo de FTP tem feito um EBCDIC para tradução ASCII dos valores de byte no campo COMP-3, que não é o que você quer. Para corrigir isso, você pode:

1) Use o modo binário para a transferência de modo a obter os dados EBCDIC matérias. Em seguida, você converter o campo COMP-3 para um número e traduzir qualquer outro texto EBCDIC no registro para ASCII. A embalados campo armazena cada dígito em meio byte com a metade byte inferior como um sinal (F é valores positivos e outros, geralmente D ou E, são negativos). Armazenar 123,4 num PIC 999,99 USO COMP-3 seria X'01234F '(três bytes) e -123 no mesmo campo é X'01230D'.

2) Ter o remetente converter o campo em um uso é sinal da exposição é a principal (ou à direita) campo numérico. Isso armazena o número como uma seqüência de dígitos numéricos EBCDIC com o sinal como um negativo separado (-) ou caracteres em branco. Todos os dígitos e o sinal traduzir corretamente para seu equivalente ASCII sobre a transferência FTP.

Peço desculpas se estou longe de base aqui, mas talvez este exemplo de código eu vou colar aqui poderia ajudá-lo. Isto veio de VBRocks ...

Imports System
Imports System.IO
Imports System.Text
Imports System.Text.Encoding



'4/20/07 submission includes a line spacing addition when a control character is used:
'   The line spacing is calculated off of the 3rd control character.
'
'   Also includes the 4/18 modification of determining end of file.

'4/26/07 submission inclues an addition of 6 to the record length when the 4th control
'   character is an 8.  This is because these records were being truncated.


'Authored by Gary A. Lima, aka. VBRocks



''' <summary>
''' Translates an EBCDIC file to an ASCII file.
''' </summary>
''' <remarks></remarks>
Public Class EBCDIC_to_ASCII_Translator

#Region " Example"

    Private Sub Example()
        'Set your source file and destination file paths
        Dim sSourcePath As String = "c:\Temp\MyEBCDICFile"
        Dim sDestinationPath As String = "c:\Temp\TranslatedFile.txt"

        Dim trans As New EBCDIC_to_ASCII_Translator()

        'If your EBCDIC file uses Control records to determine the length of a record, then this to True
        trans.UseControlRecord = True

        'If the first record of your EBCDIC file is filler (junk), then set this to True
        trans.IgnoreFirstRecord = True

        'EBCDIC files are written in block lengths, set your block length (Example:  134, 900, Etc.)
        trans.BlockLength = 900

        'This method will actually translate your source file and output it to the specified destination file path
        trans.TranslateFile(sSourcePath, sDestinationPath)


        'Here is a alternate example:
        'No Control record is used
        'trans.UseControlRecord = False

        'Translate the whole file, including the first record
        'trans.IgnoreFirstRecord = False

        'Set the block length
        'trans.BlockLength = 134

        'Translate...
        'trans.TranslateFile(sSourcePath, sDestinationPath)



        '*** Some additional methods that you can use are:

        'Trim off leading characters from left side of string (position 0 to...)
        'trans.LTrim = 15

        'Translate 1 EBCDIC character to an ASCII character
        'Dim strASCIIChar as String = trans.TranslateCharacter("S")

        'Translate an EBCDIC character array to an ASCII string
        'trans.TranslateCharacters(chrEBCDICArray)

        'Translates an EBCDIC string to an ASCII string
        'Dim strASCII As String = trans.TranslateString("EBCDIC String")


    End Sub

#End Region    'Example

    'Translate characters from EBCDIC to ASCII

    Private ASCIIEncoding As Encoding = Encoding.ASCII
    Private EBCDICEncoding As Encoding = Encoding.GetEncoding(37)  'EBCDIC

    'Block Length:  Can be fixed (Ex:  134). 
    Private miBlockLength As Integer = 0
    Private mbUseControlRec As Boolean = True        'If set to False, will return exact block length
    Private mbIgnoreFirstRecord As Boolean = True    'Will Ignore first record if set to true  (First record may be filler)
    Private miLTrim As Integer = 0

    ''' <summary>
    ''' Translates SourceFile from EBCDIC to ASCII.  Writes output to file path specified by DestinationFile parameter.
    ''' Set the BlockLength Property to designate block size to read.
    ''' </summary>
    ''' <param name="SourceFile">Enter the path of the Source File.</param>
    ''' <param name="DestinationFile">Enter the path of the Destination File.</param>
    ''' <remarks></remarks>
    Public Sub TranslateFile(ByVal SourceFile As String, ByVal DestinationFile As String)

        Dim iRecordLength As Integer     'Stores length of a record, not including the length of the Control Record (if used)
        Dim sRecord As String = ""         'Stores the actual record
        Dim iLineSpace As Integer = 1    'LineSpace:  1 for Single Space, 2 for Double Space, 3 for Triple Space...

        Dim iControlPosSix As Byte()      'Stores the 6th character of a Control Record (used to calculate record length)
        Dim iControlRec As Byte()          'Stores the EBCDIC Control Record (First 6 characters of record)
        Dim bEOR As Boolean                'End of Record Flag
        Dim bBOF As Boolean = True      'Beginning of file
        Dim iConsumedChars As Integer = 0     'Stores the number of consumed characters in the current block
        Dim bIgnoreRecord As Boolean = mbIgnoreFirstRecord   'Ignores the first record if set.

        Dim ControlArray(5) As Char         'Stores Control Record (first 6 bytes)
        Dim chrArray As Char()              'Stores characters just after read from file

        Dim sr As New StreamReader(SourceFile, EBCDICEncoding)
        Dim sw As New StreamWriter(DestinationFile)

        'Set the RecordLength to the RecordLength Property (below)
        iRecordLength = miBlockLength

        'Loop through entire file
        Do Until sr.EndOfStream = True

            'If using a Control Record, then check record for valid data.
            If mbUseControlRec = True Then
                'Read the Control Record (first 6 characters of the record)
                sr.ReadBlock(ControlArray, 0, 6)

                'Update the value of consumed (read) characters
                iConsumedChars += ControlArray.Length

                'Get the bytes of the Control Record Array
                iControlRec = EBCDICEncoding.GetBytes(ControlArray)

                'Set the line spacing  (position 3 divided by 64)
                '   (64 decimal = Single Spacing; 128 decimal = Double Spacing)
                iLineSpace = iControlRec(2) / 64


                'Check the Control record for End of File
                'If the Control record has a 8 or 10 in position 1, and a 1 in postion 2, then it is the end of the file
                If (iControlRec(0) = 8 OrElse iControlRec(0) = 10) AndAlso _
                    iControlRec(1) = 1 Then

                    If bBOF = False Then
                        Exit Do

                    Else
                        'The Beginning of file flag is set to true by default, so when the first
                        '   record is encountered, it is bypassed and the bBOF flag is set to False
                        bBOF = False

                    End If    'If bBOF = Fals

                End If    'If (iControlRec(0) = 8 OrElse



                'Set the default value for the End of Record flag to True
                '   If the Control Record has all zeros, then it's True, else False
                bEOR = True

                'If the Control record contains all zeros, bEOR will stay True, else it will be set to False
                For i As Integer = 0 To 5
                    If iControlRec(i) > 0 Then
                        bEOR = False

                        Exit For

                    End If    'If iControlRec(i) > 0

                Next    'For i As Integer = 0 To 5

                If bEOR = False Then
                    'Convert EBCDIC character to ASCII
                    'Multiply the 6th byte by 6 to get record length
                    '   Why multiply by 6?  Because it works.
                    iControlPosSix = EBCDICEncoding.GetBytes(ControlArray(5))

                    'If the 4th position of the control record is an 8, then add 6
                    '    to the record length to pick up remaining characters.
                    If iControlRec(3) = 8 Then
                        iRecordLength = CInt(iControlPosSix(0)) * 6 + 6

                    Else
                        iRecordLength = CInt(iControlPosSix(0)) * 6

                    End If

                    'Add the length of the record to the Consumed Characters counter
                    iConsumedChars += iRecordLength

                Else
                    'If the Control Record had all zeros in it, then it is the end of the Block.

                    'Consume the remainder of the block so we can continue at the beginning of the next block.
                    ReDim chrArray(miBlockLength - iConsumedChars - 1)
                    'ReDim chrArray(iRecordLength - iConsumedChars - 1)

                    'Consume (read) the remaining characters in the block.  
                    '   We are not doing anything with them because they are not actual records.
                    'sr.ReadBlock(chrArray, 0, iRecordLength - iConsumedChars)
                    sr.ReadBlock(chrArray, 0, miBlockLength - iConsumedChars)

                    'Reset the Consumed Characters counter
                    iConsumedChars = 0

                    'Set the Record Length to 0 so it will not be processed below.
                    iRecordLength = 0

                End If    ' If bEOR = False

            End If    'If mbUseControlRec = True



            If iRecordLength > 0 Then
                'Resize our array, dumping previous data.  Because Arrays are Zero (0) based, subtract 1 from the Record length.
                ReDim chrArray(iRecordLength - 1)

                'Read the specfied record length, without the Control Record, because we already consumed (read) it.
                sr.ReadBlock(chrArray, 0, iRecordLength)

                'Copy Character Array to String Array, Converting in the process, then Join the Array to a string
                sRecord = Join(Array.ConvertAll(chrArray, New Converter(Of Char, String)(AddressOf ChrToStr)), "")

                'If the record length was 0, then the Join method may return Nothing
                If IsNothing(sRecord) = False Then

                    If bIgnoreRecord = True Then
                        'Do nothing - bypass record

                        'Reset flag
                        bIgnoreRecord = False

                    Else
                        'Write the line out, LTrimming the specified number of characters.
                        If sRecord.Length >= miLTrim Then
                            sw.WriteLine(sRecord.Remove(0, miLTrim))

                        Else
                            sw.WriteLine(sRecord.Remove(0, sRecord.Length))

                        End If    ' If sRecord.Length >= miLTrim

                        'Write out the number of blank lines specified by the 3rd control character.
                        For i As Integer = 1 To iLineSpace - 1
                            sw.WriteLine("")

                        Next    'For i As Integer = 1 To iLineSpace

                    End If    'If bIgnoreRecord = True


                    'Obviously, if we have read more characters from the file than the designated size of the block,
                    '   then subtract the number of characters we have read into the next block from the block size.
                    If iConsumedChars > miBlockLength Then
                        'If iConsumedChars > iRecordLength Then
                        iConsumedChars = iConsumedChars - miBlockLength
                        'iConsumedChars = iConsumedChars - iRecordLength

                    End If

                End If    'If IsNothing(sRecord) = False

            End If    'If iRecordLength > 0

            'Allow computer to process  (works in a class module, not in a dll)
            'Application.DoEvents()

        Loop

        'Destroy StreamReader (sr)
        sr.Close()
        sr.Dispose()

        'Destroy StreamWriter (sw)
        sw.Close()
        sw.Dispose()

    End Sub



    ''' <summary>
    ''' Translates 1 EBCDIC Character (Char) to an ASCII String
    ''' </summary>
    ''' <param name="chr"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function ChrToStr(ByVal chr As Char) As String
        Dim sReturn As String = ""

        'Convert character into byte
        Dim EBCDICbyte As Byte() = EBCDICEncoding.GetBytes(chr)

        'Convert EBCDIC byte to ASCII byte
        Dim ASCIIByte As Byte() = Encoding.Convert(EBCDICEncoding, ASCIIEncoding, EBCDICbyte)

        sReturn = Encoding.ASCII.GetString(ASCIIByte)

        Return sReturn

    End Function



    ''' <summary>
    ''' Translates an EBCDIC String to an ASCII String
    ''' </summary>
    ''' <param name="sStringToTranslate"></param>
    ''' <returns>String</returns>
    ''' <remarks></remarks>
    Public Function TranslateString(ByVal sStringToTranslate As String) As String
        Dim i As Integer = 0
        Dim sReturn As New System.Text.StringBuilder()

        'Loop through the string and translate each character
        For i = 0 To sStringToTranslate.Length - 1
            sReturn.Append(ChrToStr(sStringToTranslate.Substring(i, 1)))

        Next

        Return sReturn.ToString()


    End Function



    ''' <summary>
    ''' Translates 1 EBCDIC Character (Char) to an ASCII String
    ''' </summary>
    ''' <param name="sCharacterToTranslate"></param>
    ''' <returns>String</returns>
    ''' <remarks></remarks>
    Public Function TranslateCharacter(ByVal sCharacterToTranslate As Char) As String

        Return ChrToStr(sCharacterToTranslate)

    End Function



    ''' <summary>
    ''' Translates an EBCDIC Character (Char) Array to an ASCII String
    ''' </summary>
    ''' <param name="sCharacterArrayToTranslate"></param>
    ''' <returns>String</returns>
    ''' <remarks>Remarks</remarks>
    Public Function TranslateCharacters(ByVal sCharacterArrayToTranslate As Char()) As String
        Dim sReturn As String = ""

        'Copy Character Array to String Array, Converting in the process, then Join the Array to a string
        sReturn = Join(Array.ConvertAll(sCharacterArrayToTranslate, _
                            New Converter(Of Char, String)(AddressOf ChrToStr)), "")

        Return sReturn

    End Function


    ''' <summary>
    ''' Block Length must be set.  You can set the BlockLength for specific block sizes (Ex:  134).
    ''' Set UseControlRecord = False for files with specific block sizes (Default is True)
    ''' </summary>
    ''' <value>0</value>
    ''' <returns>Integer</returns>
    ''' <remarks></remarks>
    Public Property BlockLength() As Integer
        Get
            Return miBlockLength

        End Get
        Set(ByVal value As Integer)
            miBlockLength = value

        End Set
    End Property



    ''' <summary>
    ''' Determines whether a ControlKey is used to calculate RecordLength of valid data
    ''' </summary>
    ''' <value>Default value is True</value>
    ''' <returns>Boolean</returns>
    ''' <remarks></remarks>
    Public Property UseControlRecord() As Boolean
        Get
            Return mbUseControlRec

        End Get
        Set(ByVal value As Boolean)
            mbUseControlRec = value

        End Set
    End Property



    ''' <summary>
    ''' Ignores first record if set (Default is True)
    ''' </summary>
    ''' <value>Default is True</value>
    ''' <returns>Boolean</returns>
    ''' <remarks></remarks>
    Public Property IgnoreFirstRecord() As Boolean
        Get
            Return mbIgnoreFirstRecord

        End Get

        Set(ByVal value As Boolean)
            mbIgnoreFirstRecord = value

        End Set
    End Property



    ''' <summary>
    ''' Trims the left side of every string the specfied number of characters.  Default is 0.
    ''' </summary>
    ''' <value>Default is 0.</value>
    ''' <returns>Integer</returns>
    ''' <remarks></remarks>
    Public Property LTrim() As Integer
        Get
            Return miLTrim

        End Get

        Set(ByVal value As Integer)
            miLTrim = value

        End Set
    End Property


End Class

Alguns links úteis para a tradução EBCDIC:

mesa Tradução - útil para fazer verificar alguns dos valores nos campos decimais compactados: http://www.simotime.com/asc2ebc1.htm

Lista de páginas de código no MSDN:
http://msdn.microsoft.com/en-us /library/dd317756(VS.85).aspx

E um pedaço de código para converter os campos de matriz byte em C #:

// 500 is the code page for IBM EBCDIC International 
System.Text.Encoding enc = new System.Text.Encoding(500);
string value = enc.GetString(byteArrayField);

Os campos embalados são os mesmos em EBCDIC ou ASCII. Não execute o EBCDIC à conversão ASCII sobre eles. Em .Net despejá-los em um byte [].

Você usar máscaras bit a bit e mudanças para embalar / descompactar. - Mas ops bit a bit só se aplicam a tipos inteiros em .Net então você precisa para saltar através de algumas aros

Um bom COBOL ou C artista pode apontar na direção certa.

Encontre um dos caras mais velhos e pagar suas dívidas (cerca de três cervejas deve fazê-lo).

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top