We split the numbers (word, uint32_t) into bytes and re-assemble the numbers from bytes

Поділитися
Вставка
  • Опубліковано 6 лип 2024
  • In this video, I will show 2 ways how you can split numbers that take up two or more bytes in memory into an array of single-byte numbers and then reassemble them into the original number. In the video, I demonstrate an example on numbers like word and uint32_t. But the method is also suitable for numbers like int, long and other integer types. This can be useful when data needs to be written to or transmitted to another device one byte at a time. For example, in the case of using the I2C interface and the Wire.h library. And when writing to non-volatile EEPROM memory.
    In the first method, we will use division and modulus. And in the second way, use bit operations, namely bit shift left and right. We will work in the Arduino IDE.
    Link to the sketch from the video - drive.google.com/file/d/1WdAU...
    0:00 Why do we need to split a number into bytes?
    1:18 First way to split into bytes
    4:45 Second way of splitting into bytes
  • Наука та технологія

КОМЕНТАРІ • 13

  • @KyokoToshino
    @KyokoToshino Рік тому

    Спасибо за видео! Помогло понять как разбить 4 байта на 2 по 2, чтобы передать по модбасу.

  • @user-dr7rr2qk3o
    @user-dr7rr2qk3o Рік тому

    highByte(x), lowByte(x)

  • @user-qd7rw5cj9n
    @user-qd7rw5cj9n 3 роки тому

    О, как раз недавно матрицу заполнял байтами из случайных чисел. Тоже делил. Про сдвиги как то не подумал. Пасиба попробую.Вот только как с минусовые и числами быть? Например то же 1212 но с минусом.

    • @neoalternator
      @neoalternator  3 роки тому

      Минусовое сначала привести к типу word или uint32_t в зависимости куда оно влезет. И потом обратно в свой тип. Т.е. (word)-1212, потом разбивка на байты, потом сборка и (int)полученное_значение. В результате снова будет -1212.

    • @alexshu5384
      @alexshu5384 3 роки тому

      Использовать указатели не проще?

    • @neoalternator
      @neoalternator  3 роки тому

      @@alexshu5384 указатели для разбивки на байты? Или речь о приведении типов?

    • @user-qd7rw5cj9n
      @user-qd7rw5cj9n 3 роки тому +1

      @@neoalternator Спасибо все получилось!

    • @user-qd7rw5cj9n
      @user-qd7rw5cj9n 3 роки тому

      @@alexshu5384 есть пример?

  • @BalabayUA
    @BalabayUA Рік тому

    assert (sizeof (float) == sizeof (char[4]));
    union {
    float fl;
    unsigned char ch[4];
    } u;
    u.fl = 2.456;
    printf ("float = %f
    ", u.fl);
    for (int i = 3; i >= 0; i--)
    printf ("char[%u] = 0x%.2X
    ", i, u.ch[i]);
    /* В итоге имеем
    float = 2.456000
    char[3] = 0x40
    char[2] = 0x1D
    char[1] = 0x2F
    char[0] = 0x1B */

    • @BalabayUA
      @BalabayUA Рік тому

      Кажется через union проще. И ближе к стандарту C если беспокоиться о совместимости между архитектурами/компиляторами