File: porttostr.c

package info (click to toggle)
tinyssh 20250501-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,388 kB
  • sloc: ansic: 20,245; sh: 1,582; python: 1,449; makefile: 913
file content (43 lines) | stat: -rw-r--r-- 901 bytes parent folder | download
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
/*
20130604
20241207 - reformated using clang-format
Jan Mojzis
Public domain.
*/

#include "crypto_uint16.h"
#include "porttostr.h"

/*
The 'porttostr(strbuf,port)' converts 'port' from network byte order
into the 0-terminated string. The 'port' length is always 2 bytes.
The caller must allocate at least PORTTOSTR_LEN bytes for 'strbuf'.
*/
char *porttostr(char *strbuf, const unsigned char *port) {

    long long len = 0;
    crypto_uint16 num;
    static char staticbuf[PORTTOSTR_LEN];

    if (!strbuf) strbuf = staticbuf; /* not thread-safe */

    num = port[0];
    num <<= 8;
    num |= port[1];
    do {
        num /= 10;
        ++len;
    } while (num);
    strbuf += len;

    num = port[0];
    num <<= 8;
    num |= port[1];
    do {
        *--strbuf = '0' + (num % 10);
        num /= 10;
    } while (num);

    while (len < PORTTOSTR_LEN) strbuf[len++] = 0;
    return strbuf;
}