Convert byte array to integer in Delphi

type B02 = array of [01..02] bytes;

...

var b: B02;

...

// here i read from tcp socket

socket.ReadBuffer (b, 2);

The question arises: how to convert B02 to an integer?

+4
source share
3 answers

You can declare Word / Smallint in the same memory location, for example:

var b : B02; myInt: smallint absolute B02; 

Again, is there some special reason why you are not just creating smallint and passing it to ReadBuffer instead of an array? I don’t know exactly which class you are using, but it is very similar to how you read from TStream and it will accept variables of any type along with the size in bytes. Why not just declare your buffer as the integer type you are looking for and cut out the broker?

+8
source

If the data is transmitted in the "network" order (first the first high byte first), and not in the "Intel" order (low first byte first), you can make several bytes yourself.

 uses SysUtils; var b: B02; w: word; //two bytes represent a word, not an integer socket.ReadBuffer(b, 2); WordRec(w).Hi := b[1]; WordRec(w).Lo := b[2]; 

Mghie suggested the following approach in the comments (and I agree with him):

 uses Winsock; var w: word; socket.ReadBuffer(w, 2); w := ntohs(w); 
+4
source

You can just drop it:

 var a: array[01..02] of Byte; i: Integer; begin i := PWORD(@a)^; end; 

or if you need to change the byte order:

  i := Swap(PWORD(@a)^); 
+3
source

All Articles