เวลา/ตัวเลข
การดำเนินการระดับบิต
AND/OR/XOR/NAND/NOR/XNOR/NOT และการเลื่อนบิตบนจำนวนเต็มที่มีความกว้างที่กำหนด (8/16/32/64 บิต) ในระบบเลขฐานใดก็ได้
(จำนวนบิตที่เลื่อน, เลขฐานสิบ)
Bitwise operations work directly on a number's individual bits rather than its value as a whole — the basis for permission flags, network protocols, and low-level optimization.
How to use it
- Enter one or two numbers in any base (binary, hex, decimal) and pick an operation (AND, OR, XOR, NAND, NOR, XNOR, NOT, or a shift).
- Pick a bit width (8/16/32/64 bits) — it affects how NOT and shifts behave at the number's boundaries.
- The result is shown instantly in several number bases for easy comparison.
Common uses
- Working with permission or setting flags packed into a single number (file system access rights, for example).
- Debugging a network protocol or binary format where fields are packed at the individual-bit level.
- A teaching example for understanding binary number representation and operations on it.
Things to keep in mind
The result of NOT and shifts depends on the chosen bit width — the same number gives a different result at 8-bit versus 32-bit width because of the different number of bits involved.
XOR is often used to toggle a flag — applying XOR twice with the same value returns the original.
บทความเกี่ยวกับเครื่องมือนี้: Bitwise operation: AND, OR และ XOR ทำงานอย่างไรในระดับบิต
คำถามที่พบบ่อย
AND, OR, XOR, NAND, NOR, XNOR และ NOT ต่างกันอย่างไร?
AND ให้ค่า 1 เมื่อทั้งสองบิตเป็น 1 เท่านั้น OR ให้ 1 เมื่ออย่างน้อยหนึ่งบิตเป็น 1 และ XOR ให้ 1 เมื่อบิตต่างกัน NAND/NOR/XNOR คือการปฏิเสธของสิ่งเหล่านั้น ส่วน NOT จะกลับค่าทุกบิตของตัวถูกดำเนินการเดียว
ความกว้างบิตและเครื่องหมายของตัวเลขถูกจัดการอย่างไร?
เลือกความกว้าง 8/16/32/64 บิต — การดำเนินการและการเลื่อนบิตจะเกิดขึ้นภายในช่วงนั้น ตัวเลขติดลบแสดงด้วยส่วนเติมเต็มสอง ดังนั้นผลลัพธ์ของ NOT หรือการเลื่อนบิตอาจดูไม่คาดคิดหากคุณคุ้นเคยกับสัญกรณ์ฐานสิบ
การเลื่อนซ้ายกับการเลื่อนขวาต่างกันอย่างไร?
การเลื่อนซ้าย (<<) เพิ่มศูนย์ทางขวา ซึ่งเท่ากับการคูณด้วย 2 ยกกำลังจำนวนที่เลื่อน การเลื่อนขวาอาจเป็นแบบตรรกะ (เพิ่มศูนย์ทางซ้าย) หรือแบบเลขคณิต (รักษาบิตเครื่องหมาย) — ประเภทขึ้นอยู่กับโหมดที่เลือก
ทำไมนิพจน์อย่าง "if (a & b == c)" จึงมักไม่ทำงานตามที่คาดไว้?
ในภาษาส่วนใหญ่ operator เปรียบเทียบ == มีลำดับความสำคัญสูงกว่า bitwise operator & ดังนั้นนิพจน์จะถูกประเมินเป็น "a & (b == c)" ไม่ใช่อย่างที่ผู้เขียนตั้งใจไว้ตามปกติ เพื่อหลีกเลี่ยงกับดักนี้ ให้ใส่วงเล็บอย่างชัดเจนรอบ bitwise operation เสมอ
ทำไมจึงใช้ bitwise flag แทนตัวแปร boolean แยกกัน?
ชุดแฟล็กที่รวมไว้ในตัวเลขเดียวจะจัดเก็บและส่งได้กระชับกว่า (เช่น ในโปรโตคอลเครือข่ายหรือรูปแบบไฟล์) และการตรวจสอบหรือเปลี่ยนแฟล็กเฉพาะด้วย AND/OR/XOR เป็นการดำเนินการที่รวดเร็วเพียงครั้งเดียว