OpenCPN Partial API docs
Loading...
Searching...
No Matches
ais_bitstring.cpp
Go to the documentation of this file.
1/***************************************************************************
2 * Copyright (C) 2010 by David S. Register *
3 * *
4 * This program is free software; you can redistribute it and/or modify *
5 * it under the terms of the GNU General Public License as published by *
6 * the Free Software Foundation; either version 2 of the License, or *
7 * (at your option) any later version. *
8 * *
9 * This program is distributed in the hope that it will be useful, *
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of *
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
12 * GNU General Public License for more details. *
13 * *
14 * You should have received a copy of the GNU General Public License *
15 * along with this program; if not, see <https://www.gnu.org/licenses/>. *
16 **************************************************************************/
17
24#include <cstring>
25
26#include "model/ais_bitstring.h"
27
28AisBitstring::AisBitstring(const char *str) {
29 byte_length = strlen(str);
30
31 for (int i = 0; i < byte_length; i++) {
32 bitbytes[i] = to_6bit(str[i]);
33 }
34}
35
36int AisBitstring::GetBitCount() { return byte_length * 6; }
37
38// Convert printable characters to IEC 6 bit representation
39// according to rules in IEC AIS Specification
40unsigned char AisBitstring::to_6bit(const char c) {
41 if (c < 0x30) return (unsigned char)-1;
42 if (c > 0x77) return (unsigned char)-1;
43 if ((0x57 < c) && (c < 0x60)) return (unsigned char)-1;
44
45 unsigned char cp = c;
46 cp += 0x28;
47
48 if (cp > 0x80)
49 cp += 0x20;
50 else
51 cp += 0x28;
52
53 return (unsigned char)(cp & 0x3f);
54}
55
56int AisBitstring::GetInt(int sp, int len, bool signed_flag) {
57 int acc = 0;
58 int s0p = sp - 1; // to zero base
59
60 int cp, cx, c0;
61
62 for (int i = 0; i < len; i++) {
63 acc = acc << 1;
64 cp = (s0p + i) / 6;
65 cx = bitbytes[cp]; // what if cp >= byte_length?
66 c0 = (cx >> (5 - ((s0p + i) % 6))) & 1;
67 if (i == 0 && signed_flag &&
68 c0) // if signed value and first bit is 1, pad with 1's
69 acc = ~acc;
70 acc |= c0;
71 }
72
73 return acc;
74}
75
76int AisBitstring::GetStr(int sp, int bit_len, char *dest, int max_len) {
77 // char temp_str[85];
78 char *temp_str = dest;
79
80 char acc = 0;
81 int s0p = sp - 1; // to zero base
82
83 int k = 0;
84 int cp, cx, c0, cs;
85
86 int i = 0;
87 while (i < bit_len && k < max_len) {
88 acc = 0;
89 for (int j = 0; j < 6; j++) {
90 acc = acc << 1;
91 cp = (s0p + i) / 6;
92 cx = bitbytes[cp]; // what if cp >= byte_length?
93 cs = 5 - ((s0p + i) % 6);
94 c0 = (cx >> cs) & 1;
95 acc |= c0;
96
97 i++;
98 }
99 temp_str[k] = (char)(acc & 0x3f);
100
101 if (acc < 32) temp_str[k] += 0x40;
102 k++;
103 }
104
105 temp_str[k] = 0;
106
107 return k;
108}
AIS use bitstring.
int GetInt(int sp, int len, bool signed_flag=false)
sp is starting bit, 1-based