Show the 8 bits of a byte in PHP

前端 未结 3 1380
悲&欢浪女
悲&欢浪女 2021-01-12 09:22

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

相关标签:
3条回答
  • 2021-01-12 09:48

    One more solution, this includes space between 4 digits:

    $char = 0;
    echo chunk_split(sprintf('%08b', ord($char)), 4, ' ');
    
    0 讨论(0)
  • 2021-01-12 09:55

    This should do the job:

    $bin = decbin(ord($char));
    $bin = str_pad($bin, 8, 0, STR_PAD_LEFT);
    
    0 讨论(0)
  • 2021-01-12 09:56

    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)
    
    0 讨论(0)
提交回复
热议问题