LINUX.ORG.RU

Сообщения someoneelsenotme

 

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

        int32_t qid = MimirQuery2(HERE, fileread(cooldown), hall_id);
        int32_t * value;

        MGetValue(qid, 0, 0, (void**)&value, NULL);
        result = *value;

        MFree(qid);

Периодически в value ерунда вместо указателя и система валится по sigsegv. Как определить валидность указателя?

 

someoneelsenotme
()

rpath для линкера и цепочки зависимостей

Есть либы и прога со следующими зависимостями:

A.so -> B.so -> C.elf

Собирается в отдельный каталог:

./bin
 +- A.so.1.1.115
 +- A.so.1.1 (link)
 +- A.so.1 (link)
 +- A.so (link)
 +- B.so.1.0.45
 +- B.so.1.0 (link)
 +- B.so.1 (link)
 +- B.so (link)
 +- C.elf

Запускается через LD_LIBRARY_PATH=. ./C.elf

Хочу чтобы в каталоге можно было иметь только A.so.1.1.115, B.so.1.0.45 и C.elf. и чтобы запускать через ./C.elf без переменной окружения.

Симлинки делаю руками. Библиотеки все мои, собираю одновременно с прожкой. Можно попросить линкер линковать на *.so.1.*.* и чтобы там разгреблась рекурсивная зависимость и чтобы запускать без переменной окружения?

И да, хочу относительные пути. Чтобы перенес на другую машину каталог bin хоть в /opt хоть в /tmp и все заработало

 , ,

someoneelsenotme
()

Хочу текстовый редактор

vim/emacs/nano/vi и иже с ними идут лесом.

Хочу gtk2 текстовый редактор, умеющий замену 200 000 слов без подвисаний (как mousepad, gedit валится), подсветки синтаксиса (как mousepad), вкладки (как mousepad), темы (как mousepad)

Чем не устраивает mousepad:

1) Нет вертикальной черты на 80 символах
2) Нет подсветки asm
3) Нет консоли в каталоге с файлом

 ,

someoneelsenotme
()

Как по-хитрому настроить syslog?

Хочу писать что-то вроде

"Room 1443: Door closed"
"Room 1322: Light is off"

И чтобы syslog сам расфасовывал это по файлам room_1443.log и room_1322.log

syslog так умеет? Или вообще никак? Есть только syslogd, никакого rsyslogd.

 , ,

someoneelsenotme
()

Помогите донастроить LaTeX

Захотел причаститься, поставил gummi, по зависимостям еще 200 метров, потом с доппакетами texlive-lang-cyrillic texlive-fonts-extra еще «После данной операции, объём занятого дискового пространства возрастёт на 571 MB»

Окей, пихаю следующий код:

\documentclass{article}

\usepackage[T2A]{fontenc}
\usepackage[utf8]{inputenc}
\usepackage[russian]{babel}

\title{Тестовый заголовок}
\author{Тестовый человек}
\date{Февраль 2017}
\begin{document}
   \maketitle
   Тестовое сообщение
\end{document}

Получаю:

This is pdfTeX, Version 3.1415926-2.5-1.40.14 (TeX Live 2013/Debian)
 \write18 enabled.
entering extended mode
(/home/alex/Проекты/test/LaTeX/.test.tex.swp
LaTeX2e <2011/06/27>
Babel <3.9h> and hyphenation patterns for 9 languages loaded.
(/usr/share/texlive/texmf-dist/tex/latex/base/article.cls
Document Class: article 2007/10/19 v1.4h Standard LaTeX document class
(/usr/share/texlive/texmf-dist/tex/latex/base/size10.clo))
(/usr/share/texlive/texmf-dist/tex/latex/base/fontenc.sty
(/usr/share/texlive/texmf-dist/tex/latex/cyrillic/t2aenc.def)
(/usr/share/texlive/texmf-dist/tex/latex/cyrillic/t2acmr.fd)
/usr/share/texlive/texmf-dist/tex/latex/base/fontenc.sty:100: Font T2A/cmr/m/n/
10=larm1000 at 10.0pt not loadable: Metric (TFM) file not found.
<to be read again> 
                   relax 
l.100 \fontencoding\encodingdefault\selectfont
                                              
/usr/share/texlive/texmf-dist/tex/latex/base/fontenc.sty:100:  ==> Fatal error 
occurred, no output PDF file produced!
Transcript written on /tmp/.test.tex.log.

Нагуглил что надо сделать так:

sudo mf-nowin -progname=mf "\mode:=ljfour; mag:=1; nonstopmode; input larm1000"

Получил тонну ошибок:

This is METAFONT, Version 2.718281 (TeX Live 2013/Debian)

(/home/alex/.texmf-var/fonts/source/lh/lh-t2a/larm1000.mf
(/usr/share/texlive/texmf-dist/fonts/source/lh/base/fikparm.mf
(/usr/share/texlive/texmf-dist/fonts/source/public/cm/cmbase.mf)
(/usr/share/texlive/texmf-dist/fonts/source/lh/base/lcyrbeg.mf)
(/usr/share/texlive/texmf-dist/fonts/source/lh/base/lkligtbl.mf)
>> 10

kpathsea: Running mktexmf ecrm
>> "input ecrm"
! I can't find file `ecrm'.
<scantokens> input ecrm
                       
<to be read again> 
                   ;
use_driver->...#=pt#;pt#:=true_pt#;scantokens(ss);
                                                  pt#:=true_pt#;font_identif...
l.304 use_driver(fonteq)
                        ;
Please type another input file name
! Emergency stop.
<scantokens> input ecrm
                       
<to be read again> 
                   ;
use_driver->...#=pt#;pt#:=true_pt#;scantokens(ss);
                                                  pt#:=true_pt#;font_identif...
l.304 use_driver(fonteq)
                        ;
Transcript written on larm1000.log.

uname -a
Linux alex 3.13.0-100-generic #147-Ubuntu SMP Tue Oct 18 16:49:53 UTC 2016 i686 i686 i686 GNU/Linux

 

someoneelsenotme
()

Помогите нагуглить военный стандарт написания на C

Чет вместо US Military C coding convention гуглится все что угодно кроме того что надо.

 ,

someoneelsenotme
()

Вторая версия консольной рисовалки на символах Брайля

Обновил кодовую базу, сменил систему сборки (не требует qmake сейчас, но имеет полную искоробочную поддержку QtCreator), добавил новые функции, сменил название, добавил полное соответствие с89.

https://github.com/codemeow/braxel

https://github.com/codemeow/braxel/raw/master/screen.png
https://github.com/codemeow/braxel/raw/master/screen2.png

Тестовая программка (в комплекте) рисует пару анимаций и показывает как можно работать с функцией Map (которая применяет AND/OR/XOR/etc для двух картинок). В комплекте также демонстрация загрузки из png.

Критика/идеи приветствуется, пулреквесты, замечания, баги.

Сборка: `scripts/build.sh debug` или `scripts/build.sh release`
Запуск: `scripts/run.sh`

Для QtCreator:
1. Открыть новый проект -> braxel.creator
2. Проект -> Сборка -> release/debug будет scripts/build.sh debug и release
3. Проект -> Запуск -> bin/tests/braxel-test
4. Добавить в переменные среды запуска LD_LIBRARY_PATH как путь к директории bin

tl;dr:

BrxPictureFromPNG(&tiger, "resources/tiger.png");
BrxPictureDraw(tiger, stdout);

 , ,

someoneelsenotme
()

Какой способ использования фреймворков удобнее?

Вариант I:

#include <libframe.h>
Один большой файл библитеки, все модули имеют доступ к данным друг друга, добавление нового модуля - рекомпиляция всей либы/фреймворка.
Пример: Gtk
# include <gtk/gtk.h>

Вариант II:

#include <libframe.h>
#include <libframe-window.h>
#include <libframe-button.h>
#include <libframe-sharedmemory.h>
Один core-файл и много мелких суббиблиотек, реализующих различные модули. Рекомпиляция нужного модуля не тянет рекомпиляцию всего проекта, после добавления нового модуля максимум что нужно сделать - это перезапустить приложения что его уже используют.
Пример: Qt
#include <QAction>
#include <QtEvents>
#include <QFrame>
#include <QMainWindow>
#include <QMenu>
#include <QPainter>
#include <QImage>
#include <QColor>

Пожалуйста, помогите выбрать наиболее подходящий вариант для своего проекта (содержит работу с окнами, таймерами, шаренной памятью, виджетами и пр.). Какие плюсы и минусы у каждого варианта? Сабж

 ,

someoneelsenotme
()

Братишка, я тебе средство отрисовки для консоли принес

https://github.com/codemeow/ascii-earth

Код выше демонстрирует сам принцип, размеры и байтовую карту можно совать любые. Пользуйтесь на здоровье

 , ,

someoneelsenotme
()

Помогите найти игру на NES

Была такая игрушка, название хз, была на картридже с китайским названием с китайскими же иероглифами.

Сюжет (насколько понятен из роликов):
На какие-то планеты кто-то напал, чуваки полетели их спасать, главгей летит последним. Потом оказывается что всех захватили в плен, и он один должен всех грохнуть чтобы спасти сотоварищей. Очищает планету за планетой (платформер с элементами Beat'm'Up) освобождает чуваков, на последней планете все предыдущие боссы и какая-то главзлодей-баба, которую он не осиливает и вроде как помирает, но его спасенные сотоварищи его поднимают и все вместе побеждают злодейку.

Отличительные особенности - все в скафандрах, была планета, где все горит, чуваки летали по космосу тупо с помощью скафандров, без кораблей.

 , ,

someoneelsenotme
()

Не осиливаю ASAN для QtCreator

QMAKE_CFLAGS += -fsanitize=address -fstack-protector
xxx.c:60: ошибка: undefined reference to `__asan_report_load4'
...
9000+ messages
QMAKE_CFLAGS += -fsanitize=address -fstack-protector
LIBS += lasan
:-1: ошибка: error: lasan: No such file or directory
alex@alex:~$ find /usr/lib -name *asan*
/usr/lib/gcc/i686-linux-gnu/4.8/libasan_preinit.o
/usr/lib/gcc/i686-linux-gnu/4.8/libasan.a
/usr/lib/gcc/i686-linux-gnu/4.8/libasan.so
/usr/lib/i386-linux-gnu/libasan.so.0
/usr/lib/i386-linux-gnu/libasan.so.0.0.0

ЧЯДНТ?

 ,

someoneelsenotme
()

Фреймбуфер возвращает неправильное разрешение экрана

Запускаю раз:

#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <fcntl.h>
#include <linux/fb.h>
#include <sys/mman.h>
#include <sys/ioctl.h>

int main()
{
    usleep(2 * 1000 * 1000);

    int fbfd = 0;
    struct fb_var_screeninfo vinfo;
    struct fb_fix_screeninfo finfo;
    long int screensize = 0;
    char *fbp = 0;
    int x = 0, y = 0;
    long int location = 0;

    // Open the file for reading and writing
    fbfd = open("/dev/fb0", O_RDWR);
    if (fbfd == -1) {
        perror("Error: cannot open framebuffer device");
        exit(1);
    }
    printf("The framebuffer device was opened successfully.\n");

    // Get fixed screen information
    if (ioctl(fbfd, FBIOGET_FSCREENINFO, &finfo) == -1) {
        perror("Error reading fixed information");
        exit(2);
    }

    // Get variable screen information
    if (ioctl(fbfd, FBIOGET_VSCREENINFO, &vinfo) == -1) {
        perror("Error reading variable information");
        exit(3);
    }

    printf("%dx%d, %dbpp\nVirt: %dx%d\n", vinfo.xres, vinfo.yres, vinfo.bits_per_pixel, vinfo.xres_virtual, vinfo.yres_virtual);

    // Figure out the size of the screen in bytes
    screensize = vinfo.xres * vinfo.yres * vinfo.bits_per_pixel / 8;

    // Map the device to memory
    fbp = (char *)mmap(0, screensize, PROT_READ | PROT_WRITE, MAP_SHARED,
                       fbfd, 0);
    if ((int)fbp == -1) {
        perror("Error: failed to map framebuffer device to memory");
        exit(4);
    }
    printf("The framebuffer device was mapped to memory successfully.\n");

    // Figure out where in memory to put the pixel
    while (1)
    for (y = 0; y < 300; y++)
    for (x = 0; x < 300; x++)
    {
        location = (x+vinfo.xoffset) * (vinfo.bits_per_pixel/8) +
                   (y+vinfo.yoffset) * finfo.line_length;
        if (vinfo.bits_per_pixel == 32)
        {
            *(fbp + location + vinfo   .red.offset    / 8) = 0xFF;
            *(fbp + location + vinfo .green.offset  / 8) = 0x00;
            *(fbp + location + vinfo  .blue.offset   / 8) = 0xFF;
            *(fbp + location + vinfo.transp.offset / 8) = 0x0;
        }
    }

    munmap(fbp, screensize);
    close(fbfd);
    return 0;
}
При экране в 1920х1080 получаю в ответ в консоли:
The framebuffer device was opened successfully.
640x480, 32bpp
Virt: 640x480
The framebuffer device was mapped to memory successfully.
Вот и хрен бы с ним, вот только вместо розового квадрата получаю рубленный на три части: https://s11.postimg.org/43d4h79xf/Screenshot_01_11_2016_18_36_56.png То есть на самом деле там не 640х480 а 1920х1080. Пробовал зааллоцировать по нужному разрешению - mmap шлет лесом.

 ,

someoneelsenotme
()

Фейлится fseek(file, 0, SEEK_END)

Есть несколько файлов на сервере, они читаются демоном на си. Вот так: http://pastebin.com/s7GJg3NJ

Проблема в том что пару раз за час он валится на fseek(..END):

Error while seeking for END ./queries/update_api_sound.sql. (-1)
Error while seeking for END ./queries/update_api_sound.sql. (-1)
Error while seeking for END ./queries/update_api_projector.sql. (-1)
Error while seeking for END ./queries/insert_defstack.sql. (-1)
Error while seeking for END ./queries/insert_defstack.sql. (-1)
Error while seeking for END ./queries/insert_defstack.sql. (-1)
Error while seeking for END ./queries/update_api_playserver.sql. (-1)
Error while seeking for END ./queries/insert_defstack.sql. (-1)
Error while seeking for END ./queries/update_api_projector.sql. (-1)
Error while seeking for END ./queries/update_api_projector.sql. (-1)
Error while seeking for END ./queries/insert_defstack.sql. (-1)
Error while seeking for END ./queries/insert_defstack.sql. (-1)
Error while seeking for END ./queries/update_api_sound.sql. (-1)
Error while seeking for END ./queries/insert_defstack.sql. (-1)
Error while seeking for END ./queries/update_api_sound.sql. (-1)
Error while seeking for END ./queries/update_api_sound.sql. (-1)
Error while seeking for END ./queries/insert_defstack.sql. (-1)
Думали может диск помер, написали тесты:
#include <stdio.h>
#include <string.h>

int main(int argc, char * argv[])
{
        if (!argv[1])
        {
                printf("Set filename\n");
                return 1;
        }

        int i;
        for (i = 0; i < 100000; i++)
        {
                FILE * file;
                file = fopen(argv[1], "rb");
                if (!file)
                {
                        printf("fopen failed\n");
                        return 1;
                }

                if (fseek(file, 0, SEEK_END))
                {
                        printf("fseek failed\n");
                        return 1;
                }

                printf("\r%06d: size = %d", i, ftell(file));

                fclose(file);
        }
        return 0;
}
Даже до 10 000 000 доводили - не фейлится.

В чем может быть проблема?

 

someoneelsenotme
()

С каких пор gcc требует линковать с мат либой при использовании <math.h>?

Чет всегда компилилось норм, а сегодня стандартная фигня типа:

    int i;
    for (i = 0; i < 64; i++)
    {
        printf("%f\n", sin(i + 1));
    }

Требует чтобы я при компиляции указывал -lm

 

someoneelsenotme
()

Помoгите с md5

Пытаюсь написать реализацию md5 согласно RFC:

//Note: All variables are unsigned 32 bit and wrap modulo 2^32 when calculating
var int[64] s, K

//s specifies the per-round shift amounts
s[ 0..15] := { 7, 12, 17, 22,  7, 12, 17, 22,  7, 12, 17, 22,  7, 12, 17, 22 }
s[16..31] := { 5,  9, 14, 20,  5,  9, 14, 20,  5,  9, 14, 20,  5,  9, 14, 20 }
s[32..47] := { 4, 11, 16, 23,  4, 11, 16, 23,  4, 11, 16, 23,  4, 11, 16, 23 }
s[48..63] := { 6, 10, 15, 21,  6, 10, 15, 21,  6, 10, 15, 21,  6, 10, 15, 21 }

//Use binary integer part of the sines of integers (Radians) as constants:
for i from 0 to 63
    K[i] := floor(232 × abs(sin(i + 1)))
end for
//(Or just use the following precomputed table):
K[ 0.. 3] := { 0xd76aa478, 0xe8c7b756, 0x242070db, 0xc1bdceee }
K[ 4.. 7] := { 0xf57c0faf, 0x4787c62a, 0xa8304613, 0xfd469501 }
K[ 8..11] := { 0x698098d8, 0x8b44f7af, 0xffff5bb1, 0x895cd7be }
K[12..15] := { 0x6b901122, 0xfd987193, 0xa679438e, 0x49b40821 }
K[16..19] := { 0xf61e2562, 0xc040b340, 0x265e5a51, 0xe9b6c7aa }
K[20..23] := { 0xd62f105d, 0x02441453, 0xd8a1e681, 0xe7d3fbc8 }
K[24..27] := { 0x21e1cde6, 0xc33707d6, 0xf4d50d87, 0x455a14ed }
K[28..31] := { 0xa9e3e905, 0xfcefa3f8, 0x676f02d9, 0x8d2a4c8a }
K[32..35] := { 0xfffa3942, 0x8771f681, 0x6d9d6122, 0xfde5380c }
K[36..39] := { 0xa4beea44, 0x4bdecfa9, 0xf6bb4b60, 0xbebfbc70 }
K[40..43] := { 0x289b7ec6, 0xeaa127fa, 0xd4ef3085, 0x04881d05 }
K[44..47] := { 0xd9d4d039, 0xe6db99e5, 0x1fa27cf8, 0xc4ac5665 }
K[48..51] := { 0xf4292244, 0x432aff97, 0xab9423a7, 0xfc93a039 }
K[52..55] := { 0x655b59c3, 0x8f0ccc92, 0xffeff47d, 0x85845dd1 }
K[56..59] := { 0x6fa87e4f, 0xfe2ce6e0, 0xa3014314, 0x4e0811a1 }
K[60..63] := { 0xf7537e82, 0xbd3af235, 0x2ad7d2bb, 0xeb86d391 }

//Initialize variables:
var int a0 := 0x67452301   //A
var int b0 := 0xefcdab89   //B
var int c0 := 0x98badcfe   //C
var int d0 := 0x10325476   //D

//Pre-processing: adding a single 1 bit
append "1" bit to message    
/* Notice: the input bytes are considered as bits strings,
  where the first bit is the most significant bit of the byte.[46]
  

//Pre-processing: padding with zeros
append "0" bit until message length in bits ≡ 448 (mod 512)
append original length in bits mod (2 pow 64) to message


//Process the message in successive 512-bit chunks:
for each 512-bit chunk of message
    break chunk into sixteen 32-bit words M[j], 0 ≤ j ≤ 15
//Initialize hash value for this chunk:
    var int A := a0
    var int B := b0
    var int C := c0
    var int D := d0
//Main loop:
    for i from 0 to 63
        if 0 ≤ i ≤ 15 then
            F := (B and C) or ((not B) and D)
            g := i
        else if 16 ≤ i ≤ 31
            F := (D and B) or ((not D) and C)
            g := (5×i + 1) mod 16
        else if 32 ≤ i ≤ 47
            F := B xor C xor D
            g := (3×i + 5) mod 16
        else if 48 ≤ i ≤ 63
            F := C xor (B or (not D))
            g := (7×i) mod 16
        dTemp := D
        D := C
        C := B
        B := B + leftrotate((A + F + K[i] + M[g]), s[i])
        A := dTemp
    end for
//Add this chunk's hash to result so far:
    a0 := a0 + A
    b0 := b0 + B
    c0 := c0 + C
    d0 := d0 + D
end for

var char digest[16] := a0 append b0 append c0 append d0 //(Output is in little-endian)

//leftrotate function definition
leftrotate (x, c)
    return (x << c) binary or (x >> (32-c));

Мой вариант (сначала хочу для пустого сообщения, так что на вход идет `memset(data, 0, 64)`):

typedef struct
{
    UInt32 abcd[4];
} md5_t;

static const UInt8 md5_shifts[64] = {
    7, 12, 17, 22,  7, 12, 17, 22,  7, 12, 17, 22,  7, 12, 17, 22,
    5,  9, 14, 20,  5,  9, 14, 20,  5,  9, 14, 20,  5,  9, 14, 20,
    4, 11, 16, 23,  4, 11, 16, 23,  4, 11, 16, 23,  4, 11, 16, 23,
    6, 10, 15, 21,  6, 10, 15, 21,  6, 10, 15, 21,  6, 10, 15, 21
};

static const UInt32 md5_sins[64] = {
    0xD76AA478U, 0xE8C7B756U, 0x242070DBU, 0xC1BDCEEEU,
    0xF57C0FAFU, 0x4787C62AU, 0xA8304613U, 0xFD469501U,
    0x698098D8U, 0x8B44F7AFU, 0xFFFF5BB1U, 0x895CD7BEU,
    0x6B901122U, 0xFD987193U, 0xA679438EU, 0x49B40821U,
    0xF61E2562U, 0xC040B340U, 0x265E5A51U, 0xE9B6C7AAU,
    0xD62F105DU, 0x02441453U, 0xD8A1E681U, 0xE7D3FBC8U,
    0x21E1CDE6U, 0xC33707D6U, 0xF4D50D87U, 0x455A14EDU,
    0xA9E3E905U, 0xFCEFA3F8U, 0x676F02D9U, 0x8D2A4C8AU,
    0xFFFA3942U, 0x8771F681U, 0x6D9D6122U, 0xFDE5380CU,
    0xA4BEEA44U, 0x4BDECFA9U, 0xF6BB4B60U, 0xBEBFBC70U,
    0x289B7EC6U, 0xEAA127FAU, 0xD4EF3085U, 0x04881D05U,
    0xD9D4D039U, 0xE6DB99E5U, 0x1FA27CF8U, 0xC4AC5665U,
    0xF4292244U, 0x432AFF97U, 0xAB9423A7U, 0xFC93A039U,
    0x655B59C3U, 0x8F0CCC92U, 0xFFEFF47DU, 0x85845DD1U,
    0x6FA87E4FU, 0xFE2CE6E0U, 0xA3014314U, 0x4E0811A1U,
    0xF7537E82U, 0xBD3AF235U, 0x2AD7D2BBU, 0xEB86D391U
};

static const UInt32 md5_inits[4] = {
    0x67452301U, 0xEFCDAB89U, 0x98BADCFEU, 0x10325476
};

typedef UInt32 (*md5_func_fghi)(UInt32, UInt32, UInt32);

static UInt32 md5_func_F(UInt32 x, UInt32 y, UInt32 z) { return ((x & y) | (~x & z)); }
static UInt32 md5_func_G(UInt32 x, UInt32 y, UInt32 z) { return ((x & z) | (y & ~z)); }
static UInt32 md5_func_H(UInt32 x, UInt32 y, UInt32 z) { return (x ^ y ^ z);          }
static UInt32 md5_func_I(UInt32 x, UInt32 y, UInt32 z) { return (y ^ (x | ~z));       }

static md5_func_fghi md5_fghi[4] = {
    md5_func_F, md5_func_G, md5_func_H, md5_func_I
};

typedef UInt32 (*md5_func_g1234)(UInt32);

static UInt32 md5_func_g1(UInt32 i) { return      i          ; }
static UInt32 md5_func_g2(UInt32 i) { return (5 * i + 1) % 16; }
static UInt32 md5_func_g3(UInt32 i) { return (3 * i + 5) % 16; }
static UInt32 md5_func_g4(UInt32 i) { return (7 * i    ) % 16; }

static md5_func_g1234 md5_g1234[4] = {
    md5_func_g1, md5_func_g2, md5_func_g3, md5_func_g4
};

void md5_init(md5_t * md5)
{
    memcpy(md5->abcd, md5_inits, sizeof(UInt32) * 4);
}

static void md5_process(md5_t * md5, UInt8 * data)
{
    UInt32 abcd[4];
    UInt32 block[16];
    UInt32 i, dt;

    memcpy(block, data, 16 * sizeof(UInt32));
    memcpy(abcd, md5->abcd, sizeof(UInt32) * 4);

    for (i = 0; i < 64; i++)
    {
        dt = abcd[3];
        abcd[3] = abcd[2];
        abcd[2] = abcd[1];
        abcd[1] = abcd[1] +
                  RRotationLeft32(abcd[0] +
                                  md5_fghi[i / 16](abcd[1], abcd[2], abcd[3]) +
                                  md5_sins[i] +
                                  block[md5_g1234[i / 16](i)],
                    md5_shifts[i]);
        abcd[0] = dt;
    }

    for (i = 0; i < 4; i++)
        md5->abcd[i] += abcd[i];
}

void md5_append(md5_t * md5, UInt8 * data, UInt32 length)
{
    /* test for empty message - no preprocessing */

    /* for every 512 bit chunk, no more than 1 chunk for the test */
    md5_process(md5, data);
}

Так вот получаю неверный хеш:

Data is    A4850585, B3833027, 5B4C60B2, 4835C01D
Should be: D41D8CD9, 8F00B204, E9800998, ECF8427E

Где у меня косяк? В русской википедии гвоорится что-то об установке 0х80 в конце данных, в английской такого нет. Есть тут эксперты?

 ,

someoneelsenotme
()

c89 64-bit int

Я так понял что в с89 вообще нет способа (кроме самописных типов) описать переменную 64-битной длины? long long появился в с99, а long хоть и описан в стандарте как «at least 32 bits» ни на одной известной мне архитектуре 32 бита не превышает.

 

someoneelsenotme
()

pTYPE vs TYPE * в си

Какие есть плюсы и минусы такого метода?

typedef  Bytes * pBytes;

Error RBytesRemove (pBytes bytes, UInt32 pos, UInt32 len);
Error RBytesReplace(pBytes bytes, pBytes what, pBytes by);
Error RBytesRemove (Bytes * bytes, UInt32 pos, UInt32 len);
Error RBytesReplace(Bytes * bytes, Bytes * what, Bytes * by);

ЗЫ: По значению Bytes использоваться не будет, то есть сигнатуры XXX(Bytes bytes) не будет, ибо нефиг через стек гонять структуры.

Внесите царя.

 

someoneelsenotme
()

Не токенизируется макрос через -D

#include <stdio.h>

#ifndef TEXT
#define TEXT "Text"
#endif

int main()
{
    char text[] = { " " TEXT };

    printf("%s\n", text);
    return 0;
}
alex@alex:~/Проекты/test/macrotest$ gcc ./macrotest.c 
alex@alex:~/Проекты/test/macrotest$ ./a.out 
 Text
alex@alex:~/Проекты/test/macrotest$ gcc ./macrotest.c -DTEXT="dsdd"
./macrotest.c: In function ‘main’:
<command-line>:0:6: error: expected ‘}’ before ‘dsdd’
./macrotest.c:9:25: note: in expansion of macro ‘TEXT’
     char text[] = { " " TEXT };
                         ^
alex@alex:~/Проекты/test/macrotest$ gcc ./macrotest.c -DTEXT=dsdd
./macrotest.c: In function ‘main’:
<command-line>:0:6: error: expected ‘}’ before ‘dsdd’
./macrotest.c:9:25: note: in expansion of macro ‘TEXT’
     char text[] = { " " TEXT };

Што происходит? Почему? Как?

 , ,

someoneelsenotme
()

Где/как покомпилить/позапускать для Itanium/powerpc/sparc?

Хочу проверить, корректно ли срабатывают мои ifdef'ы для этих платформ и правильно ли расставились размеры для новозаданных фиксированных размеров для с89. То есть проверить

#include <stdio.h>

#if defined(__x86_64__) || defined(_M_X64)
    typedef unsigned     char u8;
    typedef   signed     char i8;
    typedef unsigned    short u16;
    typedef   signed    short i16;
    typedef unsigned      int u32;
    typedef   signed      int i32;
#elif defined(__i386) || defined(_M_IX86)
    typedef unsigned          char u8;
    typedef   signed          char i8;
    typedef unsigned         short u16;
    typedef   signed         short i16;
    typedef unsigned           int u32;
    typedef   signed           int i32;
#endif

#if defined(__ia64) || defined(__itanium__) || defined(_M_IA64)
    typedef unsigned     char u8;
    typedef   signed     char i8;
    typedef unsigned    short u16;
    typedef   signed    short i16;
    typedef unsigned      int u32;
    typedef   signed      int i32;
#endif

// power pc/power pc64/sparc/sparc 64/arm

int main()
{
    printf("sizeof(u8)  = 1? %s\n", sizeof(u8)  == 1 ? "true" : "false");
    printf("sizeof(i8)  = 1? %s\n", sizeof(i8)  == 1 ? "true" : "false");
    printf("sizeof(u16) = 2? %s\n", sizeof(u16) == 2 ? "true" : "false");
    printf("sizeof(i16) = 2? %s\n", sizeof(i16) == 2 ? "true" : "false");
    printf("sizeof(u32) = 4? %s\n", sizeof(u32) == 4 ? "true" : "false");
    printf("sizeof(i32) = 4? %s\n", sizeof(i32) == 4 ? "true" : "false");

    return 0;
}

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

 , , , ,

someoneelsenotme
()

А какой у вас был самый забавный код?

while (parent->parent) parent = parent->parent;

 

someoneelsenotme
()

RSS подписка на новые темы