【问题标题】:Writing raw bits to a file in Lazarus将原始位写入 Lazarus 中的文件
【发布时间】:2019-12-18 16:28:02
【问题描述】:

假设我生成了一串随机排序的 1 和 0。 如果我将所述字符串写入文件,它将被写入为 ANSI 字符串,这不是我想要做的。我想将字符串中的 1 和 0 写为原始位。我怎样才能做到这一点?

【问题讨论】:

  • 您好,欢迎来到 SO。请花时间阅读How to Ask 部分,以了解如何发布一个好的问题,以便社区可以为您提供帮助。请编辑您的帖子并添加minimal, reproducible example 以及您可能遇到的任何错误或日志。

标签: data-conversion freepascal lazarus


【解决方案1】:

您可以逐个字符地遍历输入字符串,并将每个“0”替换为#0,将每个“1”替换为#1。

const
  txt = '0001010001011110101110101010000001011111';
var
  s: String;
  i: Integer;
begin
  SetLength(s, Length(txt));
  for i:=1 to Length(txt) do
    if txt[i] = '0' then
      s[i] := #0
    else if txt[i] = '1' then
      s[i] := #1
    else
    begin
      WriteLn('Unsupported character in input string');
      Halt;
    end;

  //... write to file here (you should know how to do it) ...
end;

或者您可以从每个字符中减去字符“0”的序数值并将结果转换回字符。结果将是“0”的#0或“1”的#1。

SetLength(s, Length(txt));
for i := 1 to Length(txt) do
  s[i] := char(ord(txt[i]) - ord('0'));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-07-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多