Skip to main content

swap2(value)

Swaps the byte order of a 16-bit integer

Availability

Device + Agent

Parameters

Name Type Description
value Integer Any numerical value

Returns

Integer

Description

This function takes a 16-bit integer and swaps the byte order: bytes 1 and 2 become bytes 2 and 1. The following diagram shows where bytes start out and where they end up; the numbers shown are each byte’s index in the initial sequence:

For example:

local a = 0x1A2B;
server.log(format("Before swap2(): 0x%X", a));
server.log(format(" After swap2(): 0x%X", swap2(a)));

logs:

2019-02-18 10:14:16.774 +00:00 "imp004m-BB-1": [Agent] Before swap2(): 0x1A2B
2019-02-18 10:14:16.774 +00:00 "imp004m-BB-1": [Agent]  After swap2(): 0x2B1A

Because Squirrel integers are 32 bits long, swap2() ignores the upper two bytes of a Squirrel integer passed to it and zeros these bits in the returned value. For example:

local a = 0x1A2B3C4D;
server.log(format("Before swap2(): 0x%X", a));
server.log(format(" After swap2(): 0x%X", swap2(a)));

logs:

2019-02-18 10:14:16.774 +00:00 "imp004m-BB-1": [Agent] Before swap2(): 0x1A2B3C4D
2019-02-18 10:14:16.774 +00:00 "imp004m-BB-1": [Agent]  After swap2(): 0x4D3C

Do not confuse this function with the blob library’s blob.swap2() method, which works on a target blob object not an integer parameter.