Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Show the 8 bits of a byte in PHP

Tags:

php

binary

I was wondering if there is a easy way to display the 8 bits of a byte(or char) in PHP.

For example for ASCII encoding the character '0' should return 0011 0000

Thanks for your input!

like image 258
Philipp Werminghausen Avatar asked May 26 '13 19:05

Philipp Werminghausen


People also ask

What is a 8 bits 1 byte?

The byte is a unit of digital information that most commonly consists of eight bits. Historically, the byte was the number of bits used to encode a single character of text in a computer and for this reason it is the smallest addressable unit of memory in many computer architectures.

What is 8 bits 11111111 called?

The largest number you can represent with 8 bits is 11111111, or 255 in decimal notation.

How many bits are there in an 8 byte address?

Fundamental Data Types A byte is eight bits, a word is 2 bytes (16 bits), a doubleword is 4 bytes (32 bits), and a quadword is 8 bytes (64 bits).


2 Answers

This should do the job:

$bin = decbin(ord($char));
$bin = str_pad($bin, 8, 0, STR_PAD_LEFT);
like image 97
Farkie Avatar answered Sep 18 '22 06:09

Farkie


You can use bitwise operators for that

$a='C';
for ($i=0; $i<8; $i++) {
  var_dump((ord($a) & (1<<$i))>>$i);
}

Output:

int(1)
int(1)
int(0)
int(0)
int(0)
int(0)
int(1)
int(0)
like image 31
fejese Avatar answered Sep 22 '22 06:09

fejese