How to convert a record from host to network byte order (big endian)?

前端 未结 2 1140
既然无缘
既然无缘 2020-12-21 22:49

I have a record:

  Tconnecting = record
  var
    a: int64;
    b: integer;
    c: integer;
  end;

which I need send to server using UDP pr

相关标签:
2条回答
  • 2020-12-21 23:13

    What you are actually doing is converting from host byte order to network byte order. All standard sockets libraries provide helper functions to do that.

    For example, Winsock offers htons, htonl etc. And in the opposite direction you have ntohs, ntohl etc. If you are using Indy, then the equivalent functions are GStack.HostToNetwork and GStack.NetworkToHost.

    You should serialize each field into a byte stream, with each field being transformed by the appropriate hton* function. Then you can put the byte stream on the wire.

    0 讨论(0)
  • 2020-12-21 23:31

    Assuming your code is running in a little-endian OS/Machine (like Windows/Intel), you can just reverse the individual bytes of your packet, for example, include the FMX.Types unit in your uses clause:

    type
      Tconnecting = record
        a: int64;
        b: integer;
        c: integer;
      end;
    
    procedure TForm1.Button1Click(Sender: TObject);
    var
      Packet, BEPacket: Tconnecting;
    begin
      packet.a := $0102030405060708;
      packet.b := $01020304;
      packet.c := $05060708;
      //big endian packet  
      BEPacket := Packet;
    
      ReverseBytes(@BEPacket.a, SizeOf(BePacket.a));
      ReverseBytes(@BEPacket.b, SizeOf(BePacket.b));
      ReverseBytes(@BEPacket.c, SizeOf(BePacket.c));
    
      Memo1.Lines.Add(Format('a: %16.16x => %16.16x', [Packet.a, BEPacket.a]));
      Memo1.Lines.Add(Format('b: %8.8x => %8.8x', [Packet.b, BEPacket.b]));
      Memo1.Lines.Add(Format('c: %8.8x => %8.8x', [Packet.c, BEPacket.c]));
    end;
    
    0 讨论(0)
提交回复
热议问题