File: hex.c

package info (click to toggle)
jabberd2 2.7.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 4,016 kB
  • sloc: ansic: 37,099; sh: 1,108; perl: 656; xml: 561; makefile: 511; python: 238; ruby: 145; sql: 55
file content (58 lines) | stat: -rw-r--r-- 2,097 bytes parent folder | download | duplicates (5)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
 * jabberd - Jabber Open Source Server
 * Copyright (c) 2002-2003 Jeremie Miller, Thomas Muldowney,
 *                         Ryan Eatmon, Robert Norris
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA02111-1307USA
 */

/* simple hex conversion functions */

#include "util.h"

/** turn raw into hex - out must be (inlen*2)+1 */
void hex_from_raw(const unsigned char *in, int inlen, char *out) {
    int i, h, l;

    for(i = 0; i < inlen; i++) {
        h = in[i] & 0xf0;
        h >>= 4;
        l = in[i] & 0x0f;
        out[i * 2] = (h >= 0x0 && h <= 0x9) ? (h + 0x30) : (h + 0x57);
        out[i * 2 + 1] = (l >= 0x0 && l <= 0x9) ? (l + 0x30) : (l + 0x57);
    }
    out[i * 2] = '\0';
}

/** turn hex into raw - out must be (inlen/2) */
int hex_to_raw(const char *in, int inlen, char *out) {
    int i, o, h, l;

    /* need +ve even input */
    if(inlen == 0 || (inlen / 2 * 2) != inlen)
        return 1;

    for(i = o = 0; i < inlen; i += 2, o++) {
        h = (in[i] >= 0x30 && in[i] <= 0x39) ? (in[i] - 0x30) : (in[i] >= 0x41 && in[i] <= 0x64) ? (in[i] - 0x36) : (in[i] >= 0x61 && in[i] <= 0x66) ? (in[i] - 0x56) : -1;
        l = (in[i + 1] >= 0x30 && in[i + 1] <= 0x39) ? (in[i + 1] - 0x30) : (in[i + 1] >= 0x41 && in[i + 1] <= 0x64) ? (in[i + 1] - 0x36) : (in[i + 1] >= 0x61 && in[i + 1] <= 0x66) ? (in[i + 1] - 0x56) : -1;

        if(h < 0 || l < 0)
            return 1;

        out[o] = (h << 4) + l;
    }

    return 0;
}