Is this conversion of fidelity correct?

I am reading a library ( github.com/adduc/phpmodbus ), and there is this function for converting integers to a string of little-endian or big-endian bytes:

private static function endianness($value, $endianness = 0) { if ($endianness == 0) return self::iecBYTE(($value >> 8) & 0x000000FF) . self::iecBYTE(($value & 0x000000FF)) . self::iecBYTE(($value >> 24) & 0x000000FF) . self::iecBYTE(($value >> 16) & 0x000000FF); else return self::iecBYTE(($value >> 24) & 0x000000FF) . self::iecBYTE(($value >> 16) & 0x000000FF) . self::iecBYTE(($value >> 8) & 0x000000FF) . self::iecBYTE(($value & 0x000000FF)); } 

The iecBYTE function is just chr($value & 0xFF) .

Now, maybe I'm fat, but the line from the small end looks wrong.
For example, with 0xAABBCCDD you get {CC}{DD}{AA}{BB} .

I even watched it on Wikipedia. Shouldn't it be {DD}{CC}{BB}{AA} ?

The code works , although it really bothers me. Am I misunderstanding this correctly?

+5
source share
2 answers

Having looked at IECType.php , I noticed that it converts PHP types to IEC 1131 types. The little horse first remembers the least significant bytes. What you described will make me think that the system uses 16-bit addresses.

If you look at the wiki for Endianess, mentioned in the comments of the endianess function above, then you will see a section in the section Little Endian - Atomic element size is 16 bits. One address contains two bytes (CCDD) and (AABB). The address containing (CCDD) is the least significant, so it will be listed first.

If you were working on an 8-bit system, each byte would be ordered (DDCCBBAA), because there would be one byte per address.

The wiki describes what you see in the endianess function.

  address1 |  address2
 16-bits |  16-bits
  CCDD |  Aabb
0
source

You're right. The function is wrong, although it is close. Looks like you just need to swap a few conversions. Logically, the conversion of small numbers ($ endianness == 0) is simply the inverse conversion of a large number ($ endianness! = 0).

 private static function endianness($value, $endianness = 0) { if ($endianness == 0) //little-endian return self::iecBYTE($value & 0x000000FF) . self::iecBYTE(($value >> 8) & 0x000000FF) . self::iecBYTE(($value >> 16) & 0x000000FF) . self::iecBYTE(($value >> 24) & 0x000000FF); else //big-endian return self::iecBYTE(($value >> 24) & 0x000000FF) . self::iecBYTE(($value >> 16) & 0x000000FF) . self::iecBYTE(($value >> 8) & 0x000000FF) . self::iecBYTE(($value & 0x000000FF)); } 
0
source

Source: https://habr.com/ru/post/1209565/


All Articles