【问题标题】:Please help me with pascal to c# code conversion [closed]请帮助我进行帕斯卡到 C# 代码的转换[关闭]
【发布时间】:2019-09-02 13:53:44
【问题描述】:

这是我需要转换的 Pascal 代码

function ByteToHex(InByte : Byte) : ShortString;
  const
    Digits : array[0..15] of char = '0123456789ABCDEF';
  begin
    result := Digits[InByte shr 4] + Digits[InByte and $0F];
  end;

没有使用 Delphi 的经验,但我正在努力将一个类转换为 C# 以供我使用,但我一直坚持这……

【问题讨论】:

  • 到目前为止你尝试过什么?你在哪里卡住了? FWIW,Stack Overflow 不是代码转换网站。
  • 重新发明轮子,嗯? The Hexadecimal ("X") Format Specifier
  • 与其尝试从一种语言转换为另一种语言,您可能应该描述您希望您的 c# 函数做什么 - 它可以接受哪些参数以及它应该提供什么输出。 Peter Wolf 的链接可以提供帮助,这个链接也可以:docs.microsoft.com/en-us/dotnet/api/…
  • 根据我使用 Delphi 的经验:扔掉它并从头开始编码,这是必需的。

标签: c# delphi byte


【解决方案1】:

现有的Delphi代码翻译

public static string ByteToHex(Byte InByte) {
  char[] Digits = new char[] {
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F',
  };  

  return string.Concat(Digits[InByte >> 4], Digits[InByte & 0x0F]);
}

更好的实现(你想要的只是格式化):

public static string ByteToHex(Byte InByte) => InByte.ToString("X2");

编辑:对于 Delphi 的 HiLo(参见 cmets)我们有 C#

// Second lowerest byte
public static byte Hi(int value) => (byte) ((value >> 8) & 0xFF);
// Lowerest byte
public static byte Lo(int value) => (byte) (value & 0xFF);

一般来说,程序是

  1. Shift 向右(如果需要):例如value >> 8second 最后一个字节变成 last 一个
  2. 面具0xFF:我们只想要一个byte& 0xFF
  3. 演员 int to byte: (byte)

【讨论】:

  • 再次想您的帮助... Hi(int) 和 Lo(int) 的 C# 等价物是什么?
  • Lo 和 Hi 返回整数的最低和次低字节(它们来自 16 位整数时代)
  • @Vamp_102: 在一般情况中,如果你想得到Nth last byte (N = 0, 1, 2, 3...) 你可以把public static byte ByteFromEnd(int value) => (byte) ((value >> (8 * N)) & 0xFF); 请看我的编辑 HiLo
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-07-05
  • 1970-01-01
  • 1970-01-01
  • 2020-11-07
相关资源
最近更新 更多