Laravel int to 32-bit binary (and vice versa)

Asked

Viewed 34 times

0

In an attempt to create a column with binary 32-bit numbers

/**
 * Run the migrations.
 *
 * @return void
 */
public function up()
{
    Schema::create('teams', function (Blueprint $table) {
        $table->increments('id');
        $table->char('binary_number', 32)->charset('binary'); // Em: https://stackoverflow.com/a/62615777/5675325
        $table->timestamps();

    });
}

Of note

$table->char('binary_number', 32)->charset('binary');

When I see the same through Heidisql I can see that you’re the type BINARY size 32.

inserir a descrição da imagem aqui

When creating the seeder to popular with the desired data, I tried

/**
 * Run the database seeds.
 *
 * @return void
 */
public function run()
{
   DB::table('teams')->insert([
    'id' => 1,
    'binary_number' => 2,
    'created_at' => now(),
    'updated_at' => now()
    ]);

Turns out if I use 2 or 101 on binary_number, will result in DB value 2 or 101, respectively.

How much I experience 00000000000000000000000000000010 (equivalent to 2 in 32-bit binary) and 00000000000000000000000001100101 (which equals 101 in 32-bit binary)

'binary_number' => 00000000000000000000000000000010,

then I get the value 8 and 294977 respectively.

However, what I seek is that 2 be kept as 00000000000000000000000000000010 and the 101 as 00000000000000000000000001100101.

  • 1

    294977 (decimal) = 1100101 (octal) and 8 (top) = 10 (octal)

  • @Augustovasques and if I want 2 to be stored as 0000000000000000000000000000000000000010?

  • 2

    It’s not the storage you have to worry about is the formatting while displaying the data. I am without the link I think the PHP documentation server is under maintenance but has the functions decoct() and base_convert() to the auxiliary.

1 answer

1

According to apokryphos

What you’re seeing is the number being encoded in base 8, because you’re prefixing it with a 0 (followed by more 0s) which makes 010 base 8 == 8 base 10.

In PHP to indicate that a number is binary 0b10, so your code would be:

'binary_number' => 0b00000000000000000000000000000010, // this is2 in decimal

If you want the decimal number 10 to be stored in the database, just use:

'binary_number' => 10,

Note that it seems that the translation to binary is happening at the end of the database, so it is not necessary to pass the binary number if you do not want it.

If you want to force the number to a binary string of the given length, you can use

$binaryString = str_pad(base_convert(2, 10, 2),32,'0',STR_PAD_LEFT); // '00000000000000000000000000000010'

For more details - https://www.php.net/manual/en/language.types.integer.php

Browser other questions tagged

You are not signed in. Login or sign up in order to post.