On Tuesday, 31 October 2023 at 14:43:43 UTC, Imperatorn wrote:
It might make sense to change since little endian is the most common when it comes to hardware. But big endian is most common when it comes to networking. So I guess it depends on your view of what is most common. Interacting with your local hardware or networking.

I realized that I had to make my prefer based on the most common. But I have to use Union. That's why I have to choose little.Endian. Because it is compatible with both Union and HexString. My test code works perfectly as seen below. I'm grateful to everyone who helped here and [on the other thread](https://forum.dlang.org/thread/ekpvajiablcfueyip...@forum.dlang.org).

```d
enum sampleText = "Hello D!"; // length <= 8 char

void main()
{
  //import sdb.string : UnionBytes;
  mixin UnionBytes!size_t;
  bytes.init = sampleText;

  import std.digest: toHexString;
  auto hexF = bytes.cell.toHexString;
  assert(hexF == "48656C6C6F204421");

  import std.string : format;
  auto helloD = sampleText.format!"%(%02X%)";
  assert(hexF == helloD);

  import std.stdio;
  bytes.code.writeln(": ",  helloD); /* Prints:

  2397076564600448328: 48656C6C6F204421      */

  import std.conv : hexString;
  static assert(sampleText == hexString!"48656C6C6F204421");

  //import sdb.string : readBytes;
  auto code = bytes.cell.readBytes!size_t;
  assert(code == bytes.code);

  bytes.init = code;
  code.writeln(": ", bytes); /* Prints:

  2397076564600448328: Hello D!      */

  assert(bytes[] == [72, 101, 108, 108, 111, 32, 68, 33]);

  //import sdb.string : HexString
  auto str = "0x";
  auto hex = HexString!size_t(bytes.code);
  hex.each!(chr => str ~= chr);
  str.writeln; // 0x48656C6C6F204421
}
```

My core template (UnionBytes) is initialized like this, and underneath I have the readBytes template, which also works with static arrays:

```d
// ...
      import std.range : front, popFront;
      size_t i;
      do // new version: range support
      {
        char chr;                  // default init: 0xFF
        chr &= str.front;          // masking
        code |= T(chr) << (i * 8); // shifting
        str.popFront;              // next char
      } while(++i < size);
    }

    auto opCast(Cast : T)() const
      => code;

    auto opCast(Cast : string)() const
      => this.format!"%s";

    auto toString(void delegate(in char[]) sink) const
      => sink.formattedWrite("%s", cast(char[])cell);

  }
  UnionBytes bytes;     // for mixin
}

template readBytes(T, bool big = false, R)
{        // pair endian version 2.1
  import std.bitmanip;

  static if(big) enum E = Endian.bigEndian;
  else enum E = Endian.littleEndian;

  import std.range : ElementType;
  alias ET = ElementType!R;

  auto readBytes(ref R dat)
  {
    auto data = cast(ET[])dat;
    return read!(T, E)(data);
  }
}
```

SDB@79

Reply via email to