32 bit integer to 4 bytes

Squirrel on Electric Imp

#require "JSONEncoder.class.nut:2.0.0"

local number = 1523187384;
local record = array(4);
local result = 0;
local byteArray = array(4);
local record2 = array(4);
local result2 = 0;
local byteArray2 = array(4);

// method 1 and before shift right
record[0] = ((number & 0xff000000) >> 24);
record[1] = ((number & 0x00ff0000) >> 16);
record[2] = ((number & 0x0000ff00) >> 8);
record[3] = number & 0x000000ff;
server.log("num: " + number); // num: 1523187384
server.log(JSONEncoder.encode(record)); // [90,201,254,184]

byteArray[0] = record[0] << 24;
byteArray[1] = record[1] << 16;
byteArray[2] = record[2] << 8;
byteArray[3] = record[3];
result = byteArray[0]+byteArray[1]+byteArray[2]+byteArray[3];
server.log("result: " + result); // result: 1523187384
server.log(JSONEncoder.encode(byteArray)); // [1509949440,13172736,65024,184]

// method 2 shift right before and
record2[0] = ((number >> 24) & 0xff);
record2[1] = ((number >> 16) & 0xff);
record2[2] = ((number >> 8) & 0xff);
record2[3] = number & 0xff;
server.log("num: " + number); // num: 1523187384
server.log(JSONEncoder.encode(record2)); // [90,201,254,184]

byteArray2[0] = record2[0] << 24;
byteArray2[1] = record2[1] << 16;
byteArray2[2] = record2[2] << 8;
byteArray2[3] = record2[3];
result2 = byteArray2[0]+byteArray2[1]+byteArray2[2]+byteArray2[3];
server.log("result2: " + result2); // result2: 1523187384
server.log(JSONEncoder.encode(byteArray2)); // [1509949440,13172736,65024,184]

When running the above on an Electric Imp it defaults to signed 32bit integer.

PHP

$num = 3523187384;

// method 1: and before shift right
$rec[0] = (($num & 0xff000000) >> 24);
$rec[1] = (($num & 0x00ff0000) >> 16);
$rec[2] = (($num & 0x0000ff00) >> 8);
$rec[3] = $num & 0x000000ff;
echo "num: $num\n";            // num: 3523187384
echo json_encode($rec) . "\n"; // [209,255,146,184]
$res[0] = $rec[0] << 24;
$res[1] = $rec[1] << 16;
$res[2] = $rec[2] << 8;
$res[3] = $rec[3];
$result = $res[0]+$res[1]+$res[2]+$res[3];

// method 2: shift right before and
echo "result: $result\n";       // result: 3523187384
echo json_encode($res) . "\n";  // [3506438144,16711680,37376,184]
$rec[0] = (($num >> 24) & 0xff);
$rec[1] = (($num >> 16) & 0xff);
$rec[2] = (($num >> 8) & 0xff);
$rec[3] = $num & 0xff;
echo "num: $num\n";            // num: 3523187384
echo json_encode($rec) . "\n"; // [209,255,146,184]
$res[0] = $rec[0] << 24;
$res[1] = $rec[1] << 16;
$res[2] = $rec[2] << 8;
$res[3] = $rec[3];
$result = $res[0]+$res[1]+$res[2]+$res[3];
echo "result: $result\n";       // result: 3523187384
echo json_encode($res) . "\n";  // [3506438144,16711680,37376,184]