Страницы

Поиск по вопросам

Показаны сообщения с ярлыком hex. Показать все сообщения
Показаны сообщения с ярлыком hex. Показать все сообщения

среда, 5 февраля 2020 г.

Склеивание двух чисел в формате hex в python

#python #hex


Всем привет!

Реализовал код который выводит два значения 0xffff и 0xf38c. 

def main():
    while True:
        id_device = instrument.read_registers(0x0006, 2)
        id_device.reverse()
        for i in id_device:
            print(hex(i))


Не могу их "склеить", чтоб получилось вот так - 0xfffff38С  (потом преобразую в десятичное
число). Помогите пожалуйста.
    


Ответы

Ответ 1



>>> (0xffff << 16) | 0xf38c 4294964108 >>> hex(_) '0xfffff38c' Если у вас на входе 4 байта, то можно напрямую их в int превратить (Питон 3): >>> int.from_bytes(b'\xff\xff\xf3\x8c', 'big') 4294964108 или: >>> import struct >>> struct.unpack('!I', b'\xff\xff\xf3\x8c')[0] 4294964108 Если вы хотите просто hex представление в виде строки получить (Питон 3): >>> b'\xff\xff\xf3\x8c'.hex() 'fffff38c'

Ответ 2



Если в id_device числа двухбайтовые, то можно использовать следующий код: def main(): while True: id_device = instrument.read_registers(0x0006, 2) shift=0 result=0 for i in id_device: result += i << shift shift += 16 print(hex(result))

среда, 22 января 2020 г.

Изменения цвета заднего фона при скролле

#javascript #css #hex


Написал скрипт, который при скролле меняет задний цвет страницы, но вот проблема
в том, что туда невозможно добавить код из хекса или имя оттенка цвета.

Чтобы скрипт сработал нужно написать имя (в атрибут data-color) цвета типа: yellow,
red, violet и т.д. Притом, если в атрибут data-color написать имя цвета типа french
rose (из википедии ), то это не будет работать.

Мне надо задавать цвет хексом. Подскажите, как это можно реализовать, чтобы можно
было туда написать цвет хексом или хотя бы имена цветов из ссылки которую я предоставил
работали?



$(window).scroll(function() {

  // селекторы
  var $window = $(window),
    $body = $('body'),
    $panel = $('.panel');

  //
  var scroll = $window.scrollTop() + ($window.height() / 3);

  $panel.each(function() {
    var $this = $(this);


    if ($this.position().top <= scroll && $this.position().top + $this.height() >
scroll) {

      // Удаляет все классы с body которые  с классом color-
      $body.removeClass(function(index, css) {
        return (css.match(/(^|\s)color-\S+/g) || []).join(' ');
      });

      // добавить класс активному диву
      $body.addClass('color-' + $(this).data('color'));
    }
  });


}).scroll();
/* Setting fade transition and default settings */

body {
  color: #000;
  transition: background-color 1s ease;
}


/* panel styles */

.panel {
  /* min height incase content is higher than window height */
  min-height: 100vh;
  display: flex;
  justify-content: space-around;
  align-items: center;
  font-family: sans-serif;
  /* outline: 10px solid hotpink; */
  /* turn above on to see the edge of panels */
}


/* colours */

.color-violet {
  background-color: #7A4EAB !important;
}

.color-indigo {
  background-color: #4332CF !important;
}

.color-blue {
  background-color: #2F8FED !important;
}

.color-green {
  background-color: #4DCF42 !important;
}

.color-yellow {
  background-color: #FFEA00 !important;
}

.color-orange {
  background-color: #F19031 !important;
}

.color-red {
  background-color: #F2293A !important;
}


/* styling for demo, can ignore */

body {
  text-align: center;
  font-size: 120%;
  line-height: 1.618;
}

h1,
h2 {
  font-size: 3em;
  letter-spacing: -0.05em;
  line-height: 1.1;
}

p {
  max-width: 30em;
  margin-bottom: 1.618em;
}

a {
  color: #4332CF;
}

#header {
  height: 100px;
  position: fixed;
  background-color: yellow;
  width: 100%;
  z-index: 99;
  transition: ease-in-out background-color .6s;
}

#header .logo img {
  padding: 10px 0;
}

#header .nav .nav-panel {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
}

#header .nav .nav-panel .top-panel {
  display: -webkit-box;
  display: -moz-box;
  display: -ms-flexbox;
  display: -webkit-flex;
  display: flex;
  color: #3116f8 !important;
}

#header .nav .nav-panel .top-panel span {
  line-height: 1.8;
}

#header .nav .nav-panel .top-panel a {
  font-size: 16px;
  text-decoration: none;
  font-weight: 900;
  padding: 0 10px;
}

#header .nav .nav-panel .top-panel a:hover {
  color: #3116f8 !important;
}

#header .nav .nav-panel .top-panel .langs ul {
  list-style-type: none;
}

#header .nav .nav-panel .top-panel .langs ul li a span {
  line-height: 1;
}

Magic scrolling colours

Scroll to animate the background colour of the body as a full height panel becomes visible.

I have tried to comment the code, particurly the JavaScript, as much as possible. I hope it's clear to understand.

Violet panel

Indigo panel

Blue panel

Green panel

Yellow panel

Orange panel

Red panel


Ответы

Ответ 1



Записывай цвет в data-color без #, а потом в JS добавляй при установке цвета обратно. Вроде проблем с этим никаких нет. $(window).scroll(function() { // селекторы var $window = $(window), $body = $('body'), $panel = $('.panel'); // var scroll = $window.scrollTop() + ($window.height() / 3); $panel.each(function() { var $this = $(this); if ($this.position().top <= scroll && $this.position().top + $this.height() > scroll) { // устанавливаем цвет $body.css('background-color', `#${$(this).data('color')}`); } }); }).scroll(); /* Setting fade transition and default settings */ body { color: #000; transition: background-color 1s ease; } /* panel styles */ .panel { /* min height incase content is higher than window height */ min-height: 100vh; display: flex; justify-content: space-around; align-items: center; font-family: sans-serif; /* outline: 10px solid hotpink; */ /* turn above on to see the edge of panels */ } /* styling for demo, can ignore */ body { text-align: center; font-size: 120%; line-height: 1.618; } h1, h2 { font-size: 3em; letter-spacing: -0.05em; line-height: 1.1; } p { max-width: 30em; margin-bottom: 1.618em; } a { color: #4332CF; } #header { height: 100px; position: fixed; background-color: yellow; width: 100%; z-index: 99; transition: ease-in-out background-color .6s; } #header .logo img { padding: 10px 0; } #header .nav .nav-panel { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; } #header .nav .nav-panel .top-panel { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; color: #3116f8 !important; } #header .nav .nav-panel .top-panel span { line-height: 1.8; } #header .nav .nav-panel .top-panel a { font-size: 16px; text-decoration: none; font-weight: 900; padding: 0 10px; } #header .nav .nav-panel .top-panel a:hover { color: #3116f8 !important; } #header .nav .nav-panel .top-panel .langs ul { list-style-type: none; } #header .nav .nav-panel .top-panel .langs ul li a span { line-height: 1; }

Magic scrolling colours

Scroll to animate the background colour of the body as a full height panel becomes visible.

I have tried to comment the code, particurly the JavaScript, as much as possible. I hope it's clear to understand.

Violet panel

Indigo panel

Blue panel

Green panel

Yellow panel

Orange panel

Red panel



понедельник, 30 декабря 2019 г.

C#: преобразовать строку в массив байтов

#c_sharp #конвертация #hex


Есть строка "612345". HEX-editor преобразует ее в следующий массив: {36 31 32 33
34 35 36}. Я хочу добавить эти значения (т.е. 36,31,...36) в массив байтов:

byte[] t = {0x36, 0x31, 0x32 ... 0x36}


только не хардкорно, а программно.

Я добился того, что в строке уже есть HEX-значения: "36 31 32 33 34 35 36" теперь
надо как-то добавить перед каждым "0х" и добавить в массив. Подскажите, как это сделать!
    


Ответы

Ответ 1



Так должно сработать: var s = "36 31 32 33 34 35 36"; var bytes = s.Split(' ').Select(_ => int.Parse(_, NumberStyles.HexNumber));

Ответ 2



Чтобы получить массив байт по строке, нужно воспользоваться методом Encoding.GetByteshttps://msdn.microsoft.com/en-us/library/system.text.encoding.getbytes%28v=vs.110%29.aspx Судя по значениям, тебе подойдёт ASCIIEncoding (учти, что не все символы в ней представимы) и UTF8Encoding. Учти, что .NET использует UnicodeEncoding (она же UTF16) для хранения строк, и любые преобразования не всегда однозначны, хотя well-formed строку в UTF16 можно привести в UTF8 и наоборот. Про ASCII даже такое утверждение неверно. https://msdn.microsoft.com/en-us/library/system.text.asciiencoding(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.text.utf8encoding(v=vs.110).aspx https://msdn.microsoft.com/en-us/library/system.text.unicodeencoding(v=vs.110).aspx Если ты хочешь получить генерацию кода, просто примени к массиву байт Select с приведением в 16ричную систему счисления в нужном виде и String.Join для объединения в строку.

Ответ 3



Преобразование строки в массив байт: // ожидает строку без пробелов, "612345" public static byte[] StringToByteArray(String hex) { int NumberChars = hex.Length; byte[] bytes = new byte[NumberChars / 2]; for (int i = 0; i < NumberChars; i += 2) bytes[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16); return bytes; } Обратное преобразование: public static string ByteArrayToString(byte[] ba) { StringBuilder hex = new StringBuilder(ba.Length * 2); foreach (byte b in ba) hex.AppendFormat("{0:x2}", b); return hex.ToString(); } или public static string ByteArrayToString(byte[] ba) { string hex = BitConverter.ToString(ba); return hex.Replace("-",""); } оригинальный ответ на enSO

Ответ 4



byte[] str = Encoding.Default.GetBytes("Hello world"); самый простой способ

воскресенье, 22 декабря 2019 г.

Проблема с буквой “Й” в UTF-8

#linux #mac #hex #diff


Пытаюсь сравнить два файла, оба содержат список файлов/папок, один сделан на маке,
другой на linux.
diff показывает разницу где ее на первый взгляд нет.
Перевод в hex режим показал что одна и та же буква (визуально это й)
в одной системе сформировалась след. символом d0b9 а в другой d0b8.
Может кто знает почему ? и как сравнивать в таком случае ?
    


Ответы

Ответ 1



Буква "й" может быть кодирована в unicode двумя способами: как один символ - собственно, "й" (Cyrillic Small Letter Short I), и как два символа - "и" (Cyrillic Small Letter I) и Combining Breve ("шляпка"). Это может создавать определённые проблемы при сравнении и поиске текста. Подробнее можно почитать в этой статье: Хабрахабр: «Й» вам не «и» краткое! О важности нормализации Unicode В вашем случае можно файл с "разложенной" буквой "й" перед сравнением прогнать через sed с помощью следующей команды: cat файл | sed "s/\xD0\xB8\xCC\x86/\xD0\xB9/g" (предложено участником Mike)

понедельник, 9 декабря 2019 г.

как занулить первые 4 бита в байте на java

#java #hex


Предположим что есть байт b = 63. В битах это будет 0011 1111.
Как можно занулить первые 4 бита чтобы получилось 0000 1111?
Делаю чтобы можно было приводить байты к 16-ричной системе.
Для зануления последних 4х битов использую сдвиг >>.
    


Ответы

Ответ 1



Чтобы из 0b0110_0010 получить 0b0000_0010, чтобы обнулить первые 4 бита, считая слева-направо (как люди на бумаге пишут): b &= 0b0000_1111; // & 0x0f Чтобы из 0b0110_0010 получить 0b0000_0110, чтобы обнулить первые 4 бита, считая справа-налево: b = (byte) ((b & 0b1111_0000) >> 4); // & 0xf0) >> 4 В данном случае нет разницы между >> и >>>. Для байта легко напечатать все возможные значения, чтобы выбрать желаемое поведение слева или справа очищать биты. Кстати: 63 == 0b0011_1111, а не 0b0110_0010 и даже 0x63 == 0b0110_0011 не равно 0b0110_0010.

Ответ 2



Используя, например, побитовые операторы >>>= Сдвиг вправо с заполнением нулями с присваиванием public static void main(String[] args) { byte b = 63; System.out.println(b); b >>>= 4; System.out.println(b); } Результат: 63 3

понедельник, 15 июля 2019 г.

Получение CRC-16 из массива байт

Из мануала к COM устройству есть пример:

, где 2 последних байта рассчитываются как CRC-16 первых байтов с полиномом X16-X15-X2-1 и инициализации 0xFFFF.
пользуясь онлайн калькулятором подсчета crc-16 сумм я не смог добиться этих значений. Грешу на мануал, но все алгоритмы найденные здесь дают разные результаты...


Ответ

Всё абсолютно стандартно:
#include
static unsigned short crc_16_table[256];
static void make_crc16_table(void) { unsigned short r, i, j; for (i = 0; i < 256; i++) { r = ((unsigned short) i) << 8; for (j = 0; j < 8; j++) { if (r & (1 << 15)) r = (r << 1) ^ 0x8005; else r = r << 1; } crc_16_table[i] = r; } }
static unsigned short crc16(const char *buf, size_t len) { unsigned short crc = 0xFFFF; while (len--) { crc = crc_16_table[((crc >> 8) ^ *buf++) & 0xFF] ^ (crc << 8); } return crc; }
int main() { make_crc16_table(); return printf("%X
", crc16("\x80\x01\x0C", 3)) == 1; }

понедельник, 1 апреля 2019 г.

C#: преобразовать строку в массив байтов

Есть строка "612345". HEX-editor преобразует ее в следующий массив: {36 31 32 33 34 35 36}. Я хочу добавить эти значения (т.е. 36,31,...36) в массив байтов:
byte[] t = {0x36, 0x31, 0x32 ... 0x36}
только не хардкорно, а программно
Я добился того, что в строке уже есть HEX-значения: "36 31 32 33 34 35 36" теперь надо как-то добавить перед каждым "0х" и добавить в массив. Подскажите, как это сделать!


Ответ

Так должно сработать:
var s = "36 31 32 33 34 35 36"; var bytes = s.Split(' ').Select(_ => int.Parse(_, NumberStyles.HexNumber));

воскресенье, 10 марта 2019 г.

Изменения цвета заднего фона при скролле

Написал скрипт, который при скролле меняет задний цвет страницы, но вот проблема в том, что туда невозможно добавить код из хекса или имя оттенка цвета.
Чтобы скрипт сработал нужно написать имя (в атрибут data-color) цвета типа: yellow, red, violet и т.д. Притом, если в атрибут data-color написать имя цвета типа french rose (из википедии ), то это не будет работать.
Мне надо задавать цвет хексом. Подскажите, как это можно реализовать, чтобы можно было туда написать цвет хексом или хотя бы имена цветов из ссылки которую я предоставил работали?
$(window).scroll(function() { // селекторы var $window = $(window), $body = $('body'), $panel = $('.panel'); // var scroll = $window.scrollTop() + ($window.height() / 3); $panel.each(function() { var $this = $(this); if ($this.position().top <= scroll && $this.position().top + $this.height() > scroll) { // Удаляет все классы с body которые с классом color- $body.removeClass(function(index, css) { return (css.match(/(^|\s)color-\S+/g) || []).join(' '); }); // добавить класс активному диву $body.addClass('color-' + $(this).data('color')); } }); }).scroll(); /* Setting fade transition and default settings */ body { color: #000; transition: background-color 1s ease; } /* panel styles */ .panel { /* min height incase content is higher than window height */ min-height: 100vh; display: flex; justify-content: space-around; align-items: center; font-family: sans-serif; /* outline: 10px solid hotpink; */ /* turn above on to see the edge of panels */ } /* colours */ .color-violet { background-color: #7A4EAB !important; } .color-indigo { background-color: #4332CF !important; } .color-blue { background-color: #2F8FED !important; } .color-green { background-color: #4DCF42 !important; } .color-yellow { background-color: #FFEA00 !important; } .color-orange { background-color: #F19031 !important; } .color-red { background-color: #F2293A !important; } /* styling for demo, can ignore */ body { text-align: center; font-size: 120%; line-height: 1.618; } h1, h2 { font-size: 3em; letter-spacing: -0.05em; line-height: 1.1; } p { max-width: 30em; margin-bottom: 1.618em; } a { color: #4332CF; } #header { height: 100px; position: fixed; background-color: yellow; width: 100%; z-index: 99; transition: ease-in-out background-color .6s; } #header .logo img { padding: 10px 0; } #header .nav .nav-panel { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; } #header .nav .nav-panel .top-panel { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; color: #3116f8 !important; } #header .nav .nav-panel .top-panel span { line-height: 1.8; } #header .nav .nav-panel .top-panel a { font-size: 16px; text-decoration: none; font-weight: 900; padding: 0 10px; } #header .nav .nav-panel .top-panel a:hover { color: #3116f8 !important; } #header .nav .nav-panel .top-panel .langs ul { list-style-type: none; } #header .nav .nav-panel .top-panel .langs ul li a span { line-height: 1; }

Magic scrolling colours

Scroll to animate the background colour of the body as a full height panel becomes visible.

I have tried to comment the code, particurly the JavaScript, as much as possible. I hope it's clear to understand.

Violet panel

Indigo panel

Blue panel

Green panel

Yellow panel

Orange panel

Red panel



Ответ

Записывай цвет в data-color без #, а потом в JS добавляй при установке цвета обратно. Вроде проблем с этим никаких нет.
$(window).scroll(function() { // селекторы var $window = $(window), $body = $('body'), $panel = $('.panel'); // var scroll = $window.scrollTop() + ($window.height() / 3); $panel.each(function() { var $this = $(this); if ($this.position().top <= scroll && $this.position().top + $this.height() > scroll) { // устанавливаем цвет $body.css('background-color', `#${$(this).data('color')}`); } }); }).scroll(); /* Setting fade transition and default settings */ body { color: #000; transition: background-color 1s ease; } /* panel styles */ .panel { /* min height incase content is higher than window height */ min-height: 100vh; display: flex; justify-content: space-around; align-items: center; font-family: sans-serif; /* outline: 10px solid hotpink; */ /* turn above on to see the edge of panels */ } /* styling for demo, can ignore */ body { text-align: center; font-size: 120%; line-height: 1.618; } h1, h2 { font-size: 3em; letter-spacing: -0.05em; line-height: 1.1; } p { max-width: 30em; margin-bottom: 1.618em; } a { color: #4332CF; } #header { height: 100px; position: fixed; background-color: yellow; width: 100%; z-index: 99; transition: ease-in-out background-color .6s; } #header .logo img { padding: 10px 0; } #header .nav .nav-panel { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; } #header .nav .nav-panel .top-panel { display: -webkit-box; display: -moz-box; display: -ms-flexbox; display: -webkit-flex; display: flex; color: #3116f8 !important; } #header .nav .nav-panel .top-panel span { line-height: 1.8; } #header .nav .nav-panel .top-panel a { font-size: 16px; text-decoration: none; font-weight: 900; padding: 0 10px; } #header .nav .nav-panel .top-panel a:hover { color: #3116f8 !important; } #header .nav .nav-panel .top-panel .langs ul { list-style-type: none; } #header .nav .nav-panel .top-panel .langs ul li a span { line-height: 1; }

Magic scrolling colours

Scroll to animate the background colour of the body as a full height panel becomes visible.

I have tried to comment the code, particurly the JavaScript, as much as possible. I hope it's clear to understand.

Violet panel

Indigo panel

Blue panel

Green panel

Yellow panel

Orange panel

Red panel


пятница, 16 ноября 2018 г.

Проблема с буквой “Й” в UTF-8

Пытаюсь сравнить два файла, оба содержат список файлов/папок, один сделан на маке, другой на linux. diff показывает разницу где ее на первый взгляд нет. Перевод в hex режим показал что одна и та же буква (визуально это й) в одной системе сформировалась след. символом d0b9 а в другой d0b8. Может кто знает почему ? и как сравнивать в таком случае ?


Ответ

Буква "й" может быть кодирована в unicode двумя способами: как один символ - собственно, "й" (Cyrillic Small Letter Short I), и как два символа - "и" (Cyrillic Small Letter I) и Combining Breve ("шляпка"). Это может создавать определённые проблемы при сравнении и поиске текста.
Подробнее можно почитать в этой статье: Хабрахабр: «Й» вам не «и» краткое! О важности нормализации Unicode
В вашем случае можно файл с "разложенной" буквой "й" перед сравнением прогнать через sed с помощью следующей команды:
cat файл | sed "s/\xD0\xB8\xCC\x86/\xD0\xB9/g"
(предложено участником Mike)