Microsoft MVP성태의 닷넷 이야기
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 1개 있습니다.)
(시리즈 글이 7개 있습니다.)
개발 환경 구성: 335. Octave의 명령 창에서 실행한 결과를 복사하는 방법
; https://www.sysnet.pe.kr/2/0/11309

개발 환경 구성: 388. Windows 환경에서 Octave 패키지 설치하는 방법
; https://www.sysnet.pe.kr/2/0/11622

개발 환경 구성: 674. WSL 2 환경에서 GNU Octave 설치
; https://www.sysnet.pe.kr/2/0/13319

개발 환경 구성: 675. Windows Octave 8.1.0 - Python 스크립트 연동
; https://www.sysnet.pe.kr/2/0/13320

개발 환경 구성: 676. WSL/Linux Octave - Python 스크립트 연동
; https://www.sysnet.pe.kr/2/0/13321

개발 환경 구성: 677. Octave에서 Excel read/write를 위한 io 패키지 설치
; https://www.sysnet.pe.kr/2/0/13323

.NET Framework: 2108. C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석
; https://www.sysnet.pe.kr/2/0/13324




C# - Octave의 "save -binary ..."로 생성한 바이너리 파일 분석

예를 하나 들어볼까요? ^^

>> M = magic(10)
M =

    92    99     1     8    15    67    74    51    58    40
    98    80     7    14    16    73    55    57    64    41
     4    81    88    20    22    54    56    63    70    47
    85    87    19    21     3    60    62    69    71    28
    86    93    25     2     9    61    68    75    52    34
    17    24    76    83    90    42    49    26    33    65
    23     5    82    89    91    48    30    32    39    66
    79     6    13    95    97    29    31    38    45    72
    10    12    94    96    78    35    37    44    46    53
    11    18   100    77    84    36    43    50    27    59

이렇게 Octave에서 생성한 데이터를 다른 언어, 여기서는 C#으로 가져오고 싶은 것입니다. 물론, save 명령어를 이용하면 되는데요,

>> save test.dat M

/* 출력 결과
# Created by Octave 8.1.0, Fri Apr 14 23:19:08 2023 GMT
# name: M
# type: matrix
# rows: 10
# columns: 10
 92 99 1 8 15 67 74 51 58 40
 98 80 7 14 16 73 55 57 64 41
 4 81 88 20 22 54 56 63 70 47
 85 87 19 21 3 60 62 69 71 28
 86 93 25 2 9 61 68 75 52 34
 17 24 76 83 90 42 49 26 33 65
 23 5 82 89 91 48 30 32 39 66
 79 6 13 95 97 29 31 38 45 72
 10 12 94 96 78 35 37 44 46 53
 11 18 100 77 84 36 43 50 27 59
*/

아쉽게도 텍스트 파싱을 들어가야 합니다. 이게 은근히 좀 ^^ 번거로운 작업을 수반합니다. 사실 텍스트가 사람이 보기에만 편한 것일 뿐 오히려 바이너리로 저장하는 것이 코딩은 더 쉽습니다.

Octave도 이런 옵션을 제공하는데요,

>> save -binary test.dat M

이렇게 출력한 test.dat를 분석하려면 바이너리 포맷을 알아야만 합니다. 다행히 검색해 보면 다음과 같은 글이 있는데요,

Octave binary file format specification
; https://lists.gnu.org/archive/html/help-octave/2004-11/msg00068.html

따라서 대충 코딩을 다음과 같이 할 수 있습니다.

using System.Text;

namespace Octave;

// https://lists.gnu.org/archive/html/help-octave/2004-11/msg00068.html
public struct BinaryOctaveFile
{
    public string Magic;

    public byte EndianType; /* 0: Little */

    public int OctaveVarNameLength; /* length of var name */

    public string OctaveVarName; /* var name itself*/

    public int DocLength; /* doc length (4 bytes) and doc (0 bytes) */

    public bool GlobalFlag; /* global flag (false) */

    public byte DataType; /* typically 255 */

    public int DataTypeNameLength; /* always 6 */
    public string DataTypeName; /* type is always "matrix" */

    public int Unknown1; /* FE FF FF FF */

    public int Rows;
    public int Columns;

    public double[] Data;

    public byte Unknown2; /* 0x07 */

    public static BinaryOctaveFile Read(string filePath)
    {
        BinaryOctaveFile octave = new BinaryOctaveFile();

        using (FileStream fs = File.OpenRead(filePath))
        using (BinaryReader sr = new BinaryReader(fs, Encoding.ASCII))
        {
            octave.Magic = new string(sr.ReadChars(10));
            octave.EndianType = sr.ReadByte();

            octave.OctaveVarNameLength = sr.ReadInt32();
            octave.OctaveVarName = new string(sr.ReadChars(octave.OctaveVarNameLength));

            octave.DocLength = sr.ReadInt32();
            octave.GlobalFlag = sr.ReadByte() == 1 ? true : false;
            octave.DataType = sr.ReadByte();

            octave.DataTypeNameLength = sr.ReadInt32();
            octave.DataTypeName = new string(sr.ReadChars(octave.DataTypeNameLength));

            octave.Unknown1 = sr.ReadInt32();

            octave.Rows = sr.ReadInt32();
            octave.Columns = sr.ReadInt32();

            octave.Unknown2 = sr.ReadByte();

            int dataCount = octave.Rows * octave.Columns;
            octave.Data = new double[dataCount];
            for (int i = 0; i < dataCount; i ++)
            {
                octave.Data[i] = sr.ReadDouble();
            }
        }

        return octave;
    }
}

텍스트 파일로 된 유형보다 훨씬 깔끔하죠? ^^ 자, 그래서 코딩은 다음과 같이 할 수 있습니다.

using Octave;

namespace ConsoleApp1;

internal class Program
{
    static void Main(string[] args)
    {
        BinaryOctaveFile octave = BinaryOctaveFile.Read(@"test.dat");

        // 칼럼 우선으로 저장되었기 때문에!
        for (int i = 0; i < octave.Columns; i++)
        {
            for (int j = 0; j < octave.Rows; j++)
            {
                Console.Write($"{octave.Data[j * octave.Rows + i],3} ");
            }

            Console.WriteLine();
        }
    }
}

/* 출력 결과
 92  99   1   8  15  67  74  51  58  40
 98  80   7  14  16  73  55  57  64  41
  4  81  88  20  22  54  56  63  70  47
 85  87  19  21   3  60  62  69  71  28
 86  93  25   2   9  61  68  75  52  34
 17  24  76  83  90  42  49  26  33  65
 23   5  82  89  91  48  30  32  39  66
 79   6  13  95  97  29  31  38  45  72
 10  12  94  96  78  35  37  44  46  53
 11  18 100  77  84  36  43  50  27  59
*/

조금만 코딩을 추가하면, C# 데이터를 Octave에서 읽도록 출력하거나, "MathNet.Numerics" 패키지의 Matrix와 연동하는 것도 가능할 것입니다. ^^

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/15/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...
NoWriterDateCnt.TitleFile(s)
12856정성태11/23/20218907.NET Framework: 1121. C# - 동일한 IP:Port로 바인딩 가능한 서버 소켓 [2]
12855정성태11/13/20216248개발 환경 구성: 605. Azure App Service - Kudu SSH 환경에서 FTP를 이용한 파일 전송
12854정성태11/13/20217820개발 환경 구성: 604. Azure - 윈도우 VM에서 FTP 여는 방법
12853정성태11/10/20216168오류 유형: 766. Azure App Service - JBoss 호스팅 생성 시 "This region has quota of 0 PremiumV3 instances for your subscription. Try selecting different region or SKU."
12851정성태11/1/20217570스크립트: 34. 파이썬 - MySQLdb 기본 예제 코드
12850정성태10/27/20218748오류 유형: 765. 우분투에서 pip install mysqlclient 실행 시 "OSError: mysql_config not found" 오류
12849정성태10/17/20217875스크립트: 33. JavaScript와 C#의 시간 변환 [1]
12848정성태10/17/20218838스크립트: 32. 파이썬 - sqlite3 기본 예제 코드 [1]
12847정성태10/14/20218688스크립트: 31. 파이썬 gunicorn - WORKER TIMEOUT 오류 발생
12846정성태10/7/20218466스크립트: 30. 파이썬 __debug__ 플래그 변수에 따른 코드 실행 제어
12845정성태10/6/20218312.NET Framework: 1120. C# - BufferBlock<T> 사용 예제 [5]파일 다운로드1
12844정성태10/3/20216310오류 유형: 764. MSI 설치 시 "... is accessible and not read-only." 오류 메시지
12843정성태10/3/20216765스크립트: 29. 파이썬 - fork 시 기존 클라이언트 소켓 및 스레드의 동작파일 다운로드1
12842정성태10/1/202125131오류 유형: 763. 파이썬 오류 - AttributeError: type object '...' has no attribute '...'
12841정성태10/1/20218549스크립트: 28. 모든 파이썬 프로세스에 올라오는 특별한 파일 - sitecustomize.py
12840정성태9/30/20218643.NET Framework: 1119. Entity Framework의 Join 사용 시 다중 칼럼에 대한 OR 조건 쿼리파일 다운로드1
12839정성태9/15/20219678.NET Framework: 1118. C# 11 - 제네릭 타입의 특성 적용파일 다운로드1
12838정성태9/13/20219328.NET Framework: 1117. C# - Task에 전달한 Action, Func 유형에 따라 달라지는 async/await 비동기 처리 [2]파일 다운로드1
12837정성태9/11/20218234VC++: 151. Golang - fmt.Errorf, errors.Is, errors.As 설명
12836정성태9/10/20217854Linux: 45. 리눅스 - 실행 중인 다른 프로그램의 출력을 확인하는 방법
12835정성태9/7/20219078.NET Framework: 1116. C# 10 - (15) CallerArgumentExpression 특성 추가 [2]파일 다운로드1
12834정성태9/7/20217482오류 유형: 762. Visual Studio 2019 Build Tools - 'C:\Program' is not recognized as an internal or external command, operable program or batch file.
12833정성태9/6/20216934VC++: 150. Golang - TCP client/server echo 예제 코드파일 다운로드1
12832정성태9/6/20217787VC++: 149. Golang - 인터페이스 포인터가 의미 있을까요?
12831정성태9/6/20216327VC++: 148. Golang - 채널에 따른 다중 작업 처리파일 다운로드1
12830정성태9/6/20218598오류 유형: 761. Internet Explorer에서 파일 다운로드 시 "Your current security settings do not allow this file to be downloaded." 오류
... [31]  32  33  34  35  36  37  38  39  40  41  42  43  44  45  ...