[討論] 操作Byte

看板PHP作者 (阿達)時間12年前 (2013/07/13 01:08), 編輯推噓1(1011)
留言12則, 5人參與, 最新討論串1/1
小的最近在寫網路程式 由於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)

07/13 09:15, , 1F
pack("CN", 0xBE, strlen($msg));
07/13 09:15, 1F

07/13 09:16, , 2F

07/13 15:07, , 3F
感謝:D 那如果連$msg一起pack 請問format參數是?
07/13 15:07, 3F

07/13 15:19, , 4F
我也想學byte演算,希望有更多人能討論這問題呢
07/13 15:19, 4F

07/13 15:58, , 5F
>3F 直接把 1F 的結果接上 $msg 就好
07/13 15:58, 5F

07/13 15:59, , 6F
如果不是要做二進位格式化的話就不必 pack
07/13 15:59, 6F

07/13 16:38, , 7F
Soga!! 3Q~
07/13 16:38, 7F

07/17 15:34, , 8F
可以用就好了. 不過如果以難易程度來說, 可以考慮
07/17 15:34, 8F

07/17 15:35, , 9F
$str = sprintf("%cTEST", 0xBE);
07/17 15:35, 9F

07/17 15:35, , 10F
蠻好理解的
07/17 15:35, 10F

07/17 15:37, , 11F
或者ansi color的例子 $ESC = sprintf("%c", 27);
07/17 15:37, 11F

07/17 15:38, , 12F
"{$ESC}[1;37m推 " "{$ESC}[1;31m噓"
07/17 15:38, 12F
文章代碼(AID): #1Hu3VvqH (PHP)
文章代碼(AID): #1Hu3VvqH (PHP)