作者usherII (阿達)
看板PHP
標題[討論] 操作Byte
時間Sat Jul 13 01:08:04 2013
小的最近在寫網路程式
由於Server端的要求 要我在傳過去的Json資料前加個Header
Header的格式是:
1byte(起頭) +
4byte(資料長度) +
Json資料
ex.
0xBE +
0x00000008 + '
{test:0}'
於是我寫了一個這樣的function來取得Header
// Get Header by message
function GetHeader($msg)
{
// startByte lenBytes(4) data
// 0 1 2 3 4 5 ...
// 0xBE . 0x00000000 . '{ ... }'
$startByte =
chr(0xBE);
$lenBytes = '';
$lenBytesLength = 4; // Length of lenBytes
$tempValue = strlen($msg);
for ($i = 0; $i < $lenBytesLength; $i++)
{
$lenBytes =
chr($tempValue & 0xFF) . $lenBytes;
$tempValue = floor($tempValue >> 8);
}
return $startByte . $lenBytes;
}
目前正常work
但因為我接觸PHP不久 在查資料的過程中也有發現像pack這樣相關的function
但不太會用 所以想請教有經驗的人
像這類操作byte傳輸資料的動作 有沒有更好更適合的做法?
非常感謝~
--
◢ . ______ ◣ ◣ ◢
◣ ◢ ◢ ◥█◣▲◢█◤ ◣
◥ ◥ ● │GRAVEYARD. \‧◣ ◥ █
◣◢
█ ◤ ◢ ◢◤◥█◤◥◣ ◤ ◤
' \ BILE DEMON│ '◣ ◥◥
▌◤◤ ◢ ◢▌ ◣▽◢▌ ◣
▄ ▄ ̄ ̄ ̄ ̄ ̄ ̄ ◤ ◢
█▌ ◣ ◥ ▎ ◥▌ ◤ ▊
◢◢ ▌ //\ ●● ◣◥◥ ◤
◥ ◤◤◢ ◥◥ ︵ ◤◤ ◣◣
◥ ▃▇ ▆◣▂◢▂▅≡█▄ ◣ USHER ◢ Ⅲ◥◢▅◣◤Ⅲ ◤
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 175.181.118.207
※ 編輯: usherII 來自: 175.181.118.207 (07/13 01:30)
1F:→ chaoms:pack("CN", 0xBE, strlen($msg)); 07/13 09:15
3F:→ usherII:感謝:D 那如果連$msg一起pack 請問format參數是? 07/13 15:07
4F:→ dlikeayu:我也想學byte演算,希望有更多人能討論這問題呢 07/13 15:19
5F:→ LPH66:>3F 直接把 1F 的結果接上 $msg 就好 07/13 15:58
6F:→ LPH66:如果不是要做二進位格式化的話就不必 pack 07/13 15:59
7F:→ usherII:Soga!! 3Q~ 07/13 16:38
8F:推 i9100:可以用就好了. 不過如果以難易程度來說, 可以考慮 07/17 15:34
9F:→ i9100:$str = sprintf("%cTEST", 0xBE); 07/17 15:35
10F:→ i9100:蠻好理解的 07/17 15:35
11F:→ i9100:或者ansi color的例子 $ESC = sprintf("%c", 27); 07/17 15:37
12F:→ i9100:"{$ESC}[1;37m推 " "{$ESC}[1;31m噓" 07/17 15:38