整数と1byte配列の相互変換(ビッグエンディアン)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
function p(a){ console.log(a); } function dispArrayLine_hex(a){ let s = ""; for(let i=0; i<a.length; i++){ s += "0x" + a[i].toString(16); if(a.length-1 !== i){ s += ","; } } s = "[" + s + "]"; p(s); } function swap(a, l, r){ let t = a[l]; a[l] = a[r]; a[r] = t; } function reverse(a){ let l = 0; let r = a.length-1; while(true){ if(r<=l){ break; } swap(a,l,r); l++; r--; } } function intToBytes(n){ let a = []; let cnt = 0; while(true){ a[cnt++] = n % 256; n = Math.floor(n/256); if(0===n){ break; } } // ビッグエンディアンにする reverse(a); return a; } function bytesToInt(list){ let n = 0; let keta = 1; for(let i=list.length-1; 0<=i; i--){ n += keta * list[i]; keta *= 256; } return n; } // let n = Number.MAX_SAFE_INTEGER; let n = 0x123456789abcde; p(n); let a = intToBytes(n); dispArrayLine_hex(a); let b = bytesToInt(a); p(b); |