Browse Source

Number to byte array conversions for scripts

Neal Wilson 10 years ago
parent
commit
eb71bb8776
1 changed files with 54 additions and 0 deletions
  1. 54
    0
      src/typica.w

+ 54
- 0
src/typica.w View File

@@ -2179,6 +2179,60 @@ QScriptValue QByteArray_appendString(QScriptContext *context, QScriptEngine *eng
2179 2179
 		self.append(argument<QString>(0, context)));
2180 2180
 }
2181 2181
 
2182
+@ Some protocols require manipulating larger than 8 bit numbers as a sequence
2183
+of bytes. To facilitate this, methods are provided to construct a |QByteArray|
2184
+from different sized numbers. 8 bit numbers are provided for uniformity.
2185
+
2186
+@<Function prototypes for scripting@>=
2187
+QScriptValue bytesFromInt8(QScriptContext *context, QScriptEngine *engine);
2188
+QScriptValue bytesFromInt16(QScriptContext *context, QScriptEngine *engine);
2189
+QScriptValue bytesFromInt32(QScriptContext *context, QScriptEngine *engine);
2190
+
2191
+@ These are globally available.
2192
+
2193
+@<Set up the scripting engine@>=
2194
+engine->globalObject().setProperty("bytesFromInt8", engine->newFunction(bytesFromInt8));
2195
+engine->globalObject().setProperty("bytesFromInt16", engine->newFunction(bytesFromInt16));
2196
+engine->globalObject().setProperty("bytesFromInt32", engine->newFunction(bytesFromInt32));
2197
+
2198
+@ The methods all work by casting the appropriate integer type to a |char *|
2199
+and copying the bytes to a new |QByteArray|.
2200
+
2201
+@<Functions for scripting@>=
2202
+QScriptValue bytesFromInt8(QScriptContext *context, QScriptEngine *engine)
2203
+{
2204
+	qint8 value = (qint8)(argument<int>(0, context));
2205
+	char *bytes = (char *)&value;
2206
+	QByteArray retval;
2207
+	retval.resize(1);
2208
+	retval[0] = bytes[0];
2209
+	return engine->toScriptValue<QByteArray>(retval);
2210
+}
2211
+
2212
+QScriptValue bytesFromInt16(QScriptContext *context, QScriptEngine *engine)
2213
+{
2214
+	qint16 value = (qint16)(argument<int>(0, context));
2215
+	char *bytes = (char *)&value;
2216
+	QByteArray retval;
2217
+	retval.resize(2);
2218
+	retval[0] = bytes[0];
2219
+	retval[1] = bytes[1];
2220
+	return engine->toScriptValue<QByteArray>(retval);
2221
+}
2222
+
2223
+QScriptValue bytesFromInt32(QScriptContext *context, QScriptEngine *engine)
2224
+{
2225
+	qint32 value = (qint32)(argument<int>(0, context));
2226
+	char *bytes = (char *)&value;
2227
+	QByteArray retval;
2228
+	retval.resize(4);
2229
+	retval[0] = bytes[0];
2230
+	retval[1] = bytes[1];
2231
+	retval[2] = bytes[2];
2232
+	retval[3] = bytes[3];
2233
+	return engine->toScriptValue<QByteArray>(retval);
2234
+}
2235
+
2182 2236
 @* Scripting QBuffer.
2183 2237
 
2184 2238
 \noindent Sometimes it is desirable to load a roast profile from a file. At

Loading…
Cancel
Save