Message format websocket (Arduino + Esp8266) - websocket

Update
Almost there I can receive messages I think. When the code is readable, I will put it in. Trying to send also..
Original question
I'm trying to connect my esp8266 (#38400 baud) ($3.50 wifi chip :)), to a Websocket. The chip is connected with a Arduino pro mini. This setup is OK and it works.
I am able to do a handshake, thanks to some code (https://github.com/ejeklint/ArduinoWebsocketServer).
So this is what the program has to do:
Handle handshake V
Receive message Received some unknown chars
Sending (when I'm able to receive, I will find out how to send)
I'm testing websocket with:
http://www.websocket.org/echo.html
connecting with my wifi module
ws://192.168.1.104:8000
When I send 3 x the message "aaaa" to my Arduino I receive this:
+IPD,0,10: | | | q | | b | k | | c | | |
+IPD,0,10: | | | ¦ | ¡ | 0 | P | Ç | À | Q | 1 |
+IPD,0,10: | | | _ | ò | ± | ? | > | | Ð | ^ | |
How can I decode this?
#include "sha1.h"
#include "Base64.h"
#include <SoftwareSerial.h>
#include <MemoryFree.h>
SoftwareSerial debug(8, 9); // RX, TX
void setup() {
Serial.begin(38400);
debug.begin(38400);
delay(50);
debug.println("start");
Serial.println("AT+RST");
delay(5000);
Serial.println("AT+CWMODE=1"); // NO CHANGE
delay(1500);
Serial.find("OK");
Serial.println("AT+CIPMUX=1");
Serial.find("OK");
delay(3000);
Serial.println("AT+CIPSERVER=1,8000");
boolean server = Serial.find("OK");
delay(3000);
Serial.println("AT+CIFSR"); // Display the ip please
boolean r = readLines(4);
debug.println("eind setup");
debug.println(server);
boolean found = false;
while(!found) // wait for the link
found = Serial.find("Link");
debug.println("link builded, end setup");
}
void loop() {
String key = "";
boolean isKey = Serial.find("Key: ");
if(isKey) {
debug.println("Key found!");
while(true) {
if(Serial.available()) {
char c = (char)Serial.read();
if(c == '=') {
doHandshake(key + "==");
key = "";
break;
}
if(c != '\r' || c != '\n') {
key = key + c;
}
}
}
// _________________________ PROBLEMO ____________________________________
while(true) { // So far so good. Handshake done Now wait for the message
if(Serial.available()) {
char c = (char)Serial.read();
debug.print(c);
debug.print(" | ");
}
}
}
// _________________________ /PROBLEMO ____________________________________
}
boolean readLines(int lines) {
boolean found = false;
int count = 0;
while(count < lines) {
if(Serial.available()) {
char c = (char)Serial.read();
if(c != '\r') {
debug.write(c);
} else {
count++;
}
}
}
return true;
}
bool doHandshake(String k) {
debug.println("do handshake: " + k);
char bite;
char temp[128];
char key[80];
memset(temp, '\0', sizeof(temp));
memset(key, '\0', sizeof(key));
byte counter = 0;
int myCo = 0;
while ((bite = k.charAt(myCo++)) != 0) {
key[counter++] = bite;
}
strcat(key, "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"); // Add the omni-valid GUID
Sha1.init();
Sha1.print(key);
uint8_t *hash = Sha1.result();
base64_encode(temp, (char*)hash, 20);
debug.print(temp);
int cc = -1;
while(temp[cc++] != '\0') {} // cc is length return key
cc = 165 + cc; // length return key + 165 keys for rest of header
Serial.print("AT+CIPSEND=0,");
Serial.println(129); // +30 // was 129
boolean found = false;
while(!found)
found = Serial.find(">"); // Wait until I can send
Serial.print("HTTP/1.1 101 Switching Protocols\r\n");
Serial.print("Upgrade: websocket\r\n");
Serial.print("Connection: Upgrade\r\n");
Serial.print("Sec-WebSocket-Accept: ");
Serial.print(temp);
Serial.print("\r\n\r\n");
return true;
}

I have no experience with websockets, but I think websockets uses UTF-8 while the Arduino terminal uses ASCII. I do not see in your code conversion between UTF-8 and ASCII.

I can send messages now from the websocket >> arduino. But sending is not working :(.
boolean getFrame() {
debug.println("getFrame()");
byte bite;
unsigned short payloadLength = 0;
bite = Serial.read();
frame.opcode = bite & 0xf; // Opcode
frame.isFinal = bite & 0x80; // Final frame?
bite = Serial.read();
frame.length = bite & 0x7f; // Length of payload
frame.isMasked = bite & 0x80;
// Frame complete!
if (!frame.isFinal) {
return false;
}
// First check if the frame size is within our limits.
if (frame.length > 126) {
return false;
}
// If the length part of the header is 126, it means it contains an extended length field.
// Next two bytes contain the actual payload size, so we need to get the "true" length.
if (frame.length == 126) {
byte exLengthByte1 = Serial.read();
byte exLengthByte2 = Serial.read();
payloadLength = (exLengthByte1 << 8) + exLengthByte2;
}
// If frame length is less than 126, that is the size of the payload.
else {
payloadLength = frame.length;
}
// Check if our buffer can store the payload.
if (payloadLength > MAX_RECEIVE_MESSAGE_SIZE) {
debug.println("te groot");
return false;
}
// Client should always send mask, but check just to be sure
if (frame.isMasked) {
frame.mask[0] = Serial.read();
frame.mask[1] = Serial.read();
frame.mask[2] = Serial.read();
frame.mask[3] = Serial.read();
}
// Get message bytes and unmask them if necessary
for (int i = 0; i < payloadLength; i++) {
if (frame.isMasked) {
frame.data[i] = Serial.read() ^ frame.mask[i % 4];
} else {
frame.data[i] = Serial.read();
}
}
for (int i = 0; i < payloadLength; i++) {
debug.print(frame.data[i]);
if(frame.data[i] == '/r')
break;
}
return true;
}
// !!!!!!!!!! NOT WORKING
boolean sendMessage(char *data, byte length) {
Serial.print((uint8_t) 0x1); // Txt frame opcode
Serial.print((uint8_t) length); // Length of data
for (int i = 0; i < length ; i++) {
Serial.print(data[i]);
}
delay(1);
return true;
}
See https://github.com/zoutepopcorn/esp8266-Websocket/blob/master/arduino_websocket.ino
The only problem now is the websocket format from arduino > websocket is not OK :(. But I think this is another issue / question.
WebSocket connection to 'ws://192.168.1.101:8000/?encoding=text' failed: One or more reserved bits are on: reserved1 = 0, reserved2 = 1, reserved3 = 1

What you are looking at is the first Web Socket frame ( | | | q | | b | k | | c | | |) that has been concatenated with the HTTP header. (+IPD,0,10:) The data that your delimiting with pipes (|) is unintelligible because it's not ASCII, nor is it UTF8. You must display the data after the last colon (:) as BINARY. Then it should make complete sense. I was doing exactly the same thing. It was only when I displayed the total data as binary that I "Got it".
I was using the "Web Sockets rock" demo from the web. It's an echo that just sends "Web Sockets rock" to a server that you nominate. I changed the Server address to the I.P. of my ESP8266 and started to look at the frames.
I did a little analysis for myself (same as you did) to see what the ESP8266 would send back after a successful handshake. (I got the hand shake working first)
Here is the 'post handshake' listing straight of TeraTerm-
+IPD,0,21:r¨$v%ÍF%ËVÃW (NOTE: Garbage after the :)
I expected to find "Web Sockets rock" somewhere in there.
Here is the listing converted to Binary, that I extracted from my receive buffer-
0 2B 0010 1011
1 49 0100 1001
2 50 0101 0000
3 44 0100 0100
4 2C 0010 1100
5 30 0011 0000
6 2C 0010 1100
7 32 0011 0010 (Ascii for 21 bytes to follow)
8 31 0011 0001 (Ascii for 21 bytes to follow)
9 3A 0011 1010 (Colon)
10 -7F 1000 0001 (Start of actual FRAME)
11 -71 1000 1111
12 72 0111 0010
13 -58 1010 1000
14 24 0010 0100
15 76 0111 0110
16 25 0010 0101
17 -33 1100 1101
18 46 0100 0110
19 25 0010 0101
20 1D 0001 1101
21 -35 1100 1011
22 4F 0100 1111
23 13 0001 0011
24 6 0000 0110
25 -78 1000 1000
26 56 0101 0110
27 19 0001 1001
28 11 0001 0001
29 -3D 1100 0011
30 57 0101 0111
Description of the fields- (Starting from the first byte after the Colon. 81)
// First byte has FIN bit and frame type opcode = text
// Second byte mask and payload length
// next four bytes for masking key
// So total of 6 bytes for the overhead
// The size of the payload in this case is "F" = 15 (the 4th nibble)
// So total of bytes are (6+15) = 21
// The first byte is saying> FIN bit is set. This is last frame in sequence. The OP code is 1 = TEXT data.
// The second byte is saying> MASK bit is set. The following data will be masked. The data length is "F" = 15
// The 3rd, 4th, 5th, 6th bytes is the masking key. In this case 72, A8, 24, 76.

Related

How to read the Base Framing Protocol of RFC6455?

My reference are:
Writing a WebSocket server in Java
Base Framing Protocol
Why the first byte 129 represent FIN, RSV1, RSV2, RSV3, and Opcode?
My expected result are:
The first byte is the FIN / 1 bit, RSV1 / 1 bit, RSV2 / 1 bit, RSV3 / 1 bit, Opcode / 1 bit, Mask / 1 bit. Total 9 bits.
The second byte is the Payload length. Total 7 bits.
My actual result are:
The first byte represent FIN, RSV1, RSV2, RSV3, and Opcode.
The second byte represent the Payload length.
Just to illustrate a bit.
First Byte:
Leftmost bit is the fin-bit rightmost 4 bits represents the opcode,
in this case 1=text
10000001
Second Byte:
Leftmost bit indicates if data is masked remaining seven indicate the length
10000000 here the lenght is zero
11111101 here the lenght is exactly 125
11111110 here the lenght indicator is 126 therefor the next two bytes will give you the length followed by four bytes for the mask-key
11111111 here the lenght indicator is 127 therefor the next eight bytes will give you the length followed by four bytes for the mask-key
After all this follows the masked payload.
ADDED 2021-07-19
To extract information like opcode and length, you have to apply some bit operations on the given bytes.
Below is an extraction from
https://github.com/napengam/phpWebSocketServer/blob/master/server/RFC6455.php to show how the server decodes a frame.
public function Decode($frame) {
// detect ping or pong frame, or fragments
$this->fin = ord($frame[0]) & 128;
$this->opcode = ord($frame[0]) & 15;
$length = ord($frame[1]) & 127;
if ($length <= 125) {
$moff = 2;
$poff = 6;
} else if ($length == 126) {
$l0 = ord($frame[2]) << 8;
$l1 = ord($frame[3]);
$length = ($l0 | $l1);
$moff = 4;
$poff = 8;
} else if ($length == 127) {
$l0 = ord($frame[2]) << 56;
$l1 = ord($frame[3]) << 48;
$l2 = ord($frame[4]) << 40;
$l3 = ord($frame[5]) << 32;
$l4 = ord($frame[6]) << 24;
$l5 = ord($frame[7]) << 16;
$l6 = ord($frame[8]) << 8;
$l7 = ord($frame[9]);
$length = ( $l0 | $l1 | $l2 | $l3 | $l4 | $l5 | $l6 | $l7);
$moff = 10;
$poff = 14;
}
$masks = substr($frame, $moff, 4);
$data = substr($frame, $poff, $length); // hgs 30.09.2016
$text = '';
$m0 = $masks[0];
$m1 = $masks[1];
$m2 = $masks[2];
$m3 = $masks[3];
for ($i = 0; $i < $length;) {
$text .= $data[$i++] ^ $m0;
if ($i < $length) {
$text .= $data[$i++] ^ $m1;
if ($i < $length) {
$text .= $data[$i++] ^ $m2;
if ($i < $length) {
$text .= $data[$i++] ^ $m3;
}
}
}
}
return $text;
}
In https://github.com/napengam/phpWebSocketServer/blob/master/phpClient/websocketCore.php you will find encode and decode for the client.

What is the meaning of `x & -x`? [duplicate]

What is the meaning of (number) & (-number)? I have searched it but was unable to find the meaning
I want to use i & (-i) in for loop like:
for (i = 0; i <= n; i += i & (-i))
Assuming 2's complement (or that i is unsigned), -i is equal to ~i+1.
i & (~i + 1) is a trick to extract the lowest set bit of i.
It works because what +1 actually does is to set the lowest clear bit, and clear all bits lower than that. So the only bit that is set in both i and ~i+1 is the lowest set bit from i (that is, the lowest clear bit in ~i). The bits lower than that are clear in ~i+1, and the bits higher than that are non-equal between i and ~i.
Using it in a loop seems odd unless the loop body modifies i, because i = i & (-i) is an idempotent operation: doing it twice gives the same result again.
[Edit: in a comment elsewhere you point out that the code is actually i += i & (-i). So what that does for non-zero i is to clear the lowest group of set bits of i, and set the next clear bit above that, for example 101100 -> 110000. For i with no clear bit higher than the lowest set bit (including i = 0), it sets i to 0. So if it weren't for the fact that i starts at 0, each loop would increase i by at least twice as much as the previous loop, sometimes more, until eventually it exceeds n and breaks or goes to 0 and loops forever.
It would normally be inexcusable to write code like this without a comment, but depending on the domain of the problem maybe this is an "obvious" sequence of values to loop over.]
I thought I'd just take a moment to show how this works. This code gives you the lowest set bit's value:
int i = 0xFFFFFFFF; //Last byte is 1111(base 2), -1(base 10)
int j = -i; //-(-1) == 1
int k = i&j; // 1111(2) = -1(10)
// & 0001(2) = 1(10)
// ------------------
// 0001(2) = 1(10). So the lowest set bit here is the 1's bit
int i = 0x80; //Last 2 bytes are 1000 0000(base 2), 128(base 10)
int j = -i; //-(128) == -128
int k = i&j; // ...0000 0000 1000 0000(2) = 128(10)
// & ...1111 1111 1000 0000(2) = -128(10)
// ---------------------------
// 1000 0000(2) = 128(10). So the lowest set bit here is the 128's bit
int i = 0xFFFFFFC0; //Last 2 bytes are 1100 0000(base 2), -64(base 10)
int j = -i; //-(-64) == 64
int k = i&j; // 1100 0000(2) = -64(10)
// & 0100 0000(2) = 64(10)
// ------------------
// 0100 0000(2) = 64(10). So the lowest set bit here is the 64's bit
It works the same for unsigned values, the result is always the lowest set bit's value.
Given your loop:
for(i=0;i<=n;i=i&(-i))
There are no bits set (i=0) so you're going to get back a 0 for the increment step of this operation. So this loop will go on forever unless n=0 or i is modified.
Assuming that negative values are using two's complement. Then -number can be calculated as (~number)+1, flip the bits and add 1.
For example if number = 92. Then this is what it would look like in binary:
number 0000 0000 0000 0000 0000 0000 0101 1100
~number 1111 1111 1111 1111 1111 1111 1010 0011
(~number) + 1 1111 1111 1111 1111 1111 1111 1010 0100
-number 1111 1111 1111 1111 1111 1111 1010 0100
(number) & (-number) 0000 0000 0000 0000 0000 0000 0000 0100
You can see from the example above that (number) & (-number) gives you the least bit.
You can see the code run online on IDE One: http://ideone.com/WzpxSD
Here is some C code:
#include <iostream>
#include <bitset>
#include <stdio.h>
using namespace std;
void printIntBits(int num);
void printExpression(char *text, int value);
int main() {
int number = 92;
printExpression("number", number);
printExpression("~number", ~number);
printExpression("(~number) + 1", (~number) + 1);
printExpression("-number", -number);
printExpression("(number) & (-number)", (number) & (-number));
return 0;
}
void printExpression(char *text, int value) {
printf("%-20s", text);
printIntBits(value);
printf("\n");
}
void printIntBits(int num) {
for(int i = 0; i < 8; i++) {
int mask = (0xF0000000 >> (i * 4));
int portion = (num & mask) >> ((7 - i) * 4);
cout << " " << std::bitset<4>(portion);
}
}
Also here is a version in C# .NET: https://dotnetfiddle.net/ai7Eq6
The operation i & -i is used for isolating the least significant non-zero bit of the corresponding integer.
In binary notation num can be represented as a1b, where a represents binary digits before the last bit and b represents zeroes after the last bit.
-num is equal to (a1b)¯ + 1 = a¯0b¯ + 1. b consists of all zeroes, so b¯ consists of all ones.
-num = (a1b)¯ + 1 => a¯0b¯ + 1 => a¯0(0…0)¯ + 1 => ¯0(1…1) + 1 => a¯1(0…0) => a¯1b
Now, num & -num => a1b & a¯1b => (0..0)1(0..0)
For e.g. if i = 5
| iteration | i | last bit position | i & -i|
|-------- |--------|-------- |-----|
| 1 | 5 = 101 | 0 | 1 (2^0)|
| 2 | 6 = 110 | 1 | 2 (2^1)|
| 3 | 8 = 1000 | 3 | 8 (2^3)|
| 4 | 16 = 10000 | 4 | 16 (2^4)|
| 5 | 32 = 100000 | 5 | 32 (2^5)|
This operation in mainly used in Binary Indexed Trees to move up and down the tree
PS: For some reason stackoverflow is treating table as code :(

How do I make this program work for input >10 for the USACO Training Pages Square Palindromes?

Problem Statement -
Given a number base B (2 <= B <= 20 base 10), print all the integers N (1 <= N <= 300 base 10) such that the square of N is palindromic when expressed in base B; also print the value of that palindromic square. Use the letters 'A', 'B', and so on to represent the digits 10, 11, and so on.
Print both the number and its square in base B.
INPUT FORMAT
A single line with B, the base (specified in base 10).
SAMPLE INPUT
10
OUTPUT FORMAT
Lines with two integers represented in base B. The first integer is the number whose square is palindromic; the second integer is the square itself. NOTE WELL THAT BOTH INTEGERS ARE IN BASE B!
SAMPLE OUTPUT
1 1
2 4
3 9
11 121
22 484
26 676
101 10201
111 12321
121 14641
202 40804
212 44944
264 69696
My code works for all inputs <=10, however, gives me some weird output for inputs >10.
My Code-
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
int baseToBase(int num, int base) //accepts a number in base 10 and the base to be converted into as arguments
{
int result=0, temp=0, i=1;
while(num>0)
{
result = result + (num%base)*pow(10, i);
i++;
num = num/base;
}
result/=10;
return result;
}
long long int isPalin(int n, int base) //checks the palindrome
{
long long int result=0, temp, num=n*n, x=n*n;
num = baseToBase(num, base);
x = baseToBase(x, base);
while(num)
{
temp=num%10;
result = result*10 + temp;
num/=10;
}
if(x==result)
return x;
else
return 0;
}
int main()
{
int base, i, temp;
long long int sq;
cin >> base;
for(i=1; i<=300; i++)
{
temp=baseToBase(i, base);
sq=isPalin(i, base);
if(sq!=0)
cout << temp << " " << sq << endl;
}
return 0;
}
For input = 11, the answer should be
1 1
2 4
3 9
6 33
11 121
22 484
24 565
66 3993
77 5335
101 10201
111 12321
121 14641
202 40804
212 44944
234 53535
While my answer is
1 1
2 4
3 9
6 33
11 121
22 484
24 565
66 3993
77 5335
110 10901
101 10201
111 12321
121 14641
209 40304
202 40804
212 44944
227 50205
234 53535
There is a difference in my output and the required one as 202 shows under 209 and 110 shows up before 101.
Help appreciated, thanks!
a simple example for B = 11 to show error in your base conversion is for i = 10 temp should be A but your code calculates temp = 10. Cause in we have only 10 symbols 0-9 to perfectly show every number in base 10 or lower but for bases greater than that you have to use other symbols to represent a different digit like 'A', 'B' and so on. problem description clearly states that. Hope You will be able to fix your code now by modifying your int baseToBase(int num, int base)function.

Is there any good and stable online SMS to PDU converter?

I'm looking for a nice online converter which could work with several modems. The problem i'm dealing with - i can't send sms in pdu mode (with Cinterion BGS-2T). Tried with my own library (still working on it) and several online converters such as:
http://www.smartposition.nl/resources/sms_pdu.html
http://m2msupport.net/m2msupport/module-tester/
http://hardisoft.ru/soft/otpravka-sms-soobshhenij-v-formate-pdu-teoriya-s-primerami-na-c-chast-1/
User data seems to be encoded well (same result everywhere), but the first part of TPDU (with PDU-Type, TP-MR, ...) may be a little bit variable (but never works, damn).
Few moments:
The modem definitely supports pdu mode.
There is cash on balance.
Modem responses on "AT+CMGS" with ">" and it responses on PDU string with "\r\nOK\r\n", but didn't responds with "+CMGS" (and of course i'm not receiving my sms).
If it necessary here is part of my own code:
void get_pdu_string(sms_descriptor* sms, char dst[]) {
char tempnum[8] = "";
char* pTemp = dst;
uint8_t i = 0;
// SMSC
//*pTemp++ = 0x00;
// PDU-Type
*pTemp++ = (0<<TP_MTIH) | (1<<TP_MTIL); // MTI = 01 - outbox sms
// TP-MR
*pTemp++ = 0x00; // unnecessary
// TP-DA
*pTemp++ = strlen(sms->to_number); // address number length
*pTemp++ = 0x91; // address number format (0x91 - international)
gsm_number_swap(sms->to_number,tempnum);
i = (((*(pTemp-2) & 0x01) == 0x01)? (*(pTemp-2)+1) : *(pTemp-2))>>1;
strncpy(pTemp, tempnum, i ); // address number
pTemp += i;
// TP-PID
*pTemp++ = 0;
// TP-DCS
switch(sms->encoding) {
case SMS_7BIT_ENC:
*pTemp++ = 0x00;
break;
case SMS_UCS2_ENC:
*pTemp++ = 0x08;
break;
}
if (sms->flash == 1)
*(pTemp-1) |= 0x10;
// TP-VP
// skip if does not need
// TP-UDL
switch(sms->encoding) {
case SMS_7BIT_ENC:
*pTemp++ = strlen(sms->msg);
break;
case SMS_UCS2_ENC:
*pTemp++ = strlen(sms->msg) << 1;
break;
}
// TP-UD
switch(sms->encoding) {
case SMS_7BIT_ENC: {
char packed_msg[140] = "";
char* pMsg = packed_msg;
gsm_7bit_enc(sms->msg, packed_msg);
while(*pMsg != 0)
*pTemp++ = *pMsg++;
} break;
case SMS_UCS2_ENC: {
wchar_t wmsg[70] = L"";
wchar_t* pMsg = wmsg;
strtoucs2(sms->msg, wmsg, METHOD_TABLE);
while(*pMsg != 0) {
*pTemp++ = (char) (*pMsg >> 8);
*pTemp++ = (char) (*pMsg++);
}
} break;
}
*pTemp = 0x1A;
return;
}
Example of my routine work:
To: 380933522620
Message: Hello! Test SMS in GSM-7
Encoded PDU string:
00 01 00 0C 81 83 90 33 25 62 02 00 00 18 C8 32 9B FD 0E 81 A8 E5 39 1D 34 6D 4E 41 69 37 E8 38 6D B6 6E 1A
Details about PDU string:
1. 00 - skipped SMSC
2. 01 - PDU-Type
3. 00 - TP-MR
4. 0C - length of To number.
5. 81 - type of number (unknown, also tried 0x91 which is international)
6. 83 90 33 25 62 02 - To number
7. 00 - TP-PID
8. 00 - TP-DCS (GSM 7bit, default SMS class)
9. 18 - TP-UD (24 letters)
10. C8 32 ... B6 6E - packed message
11. 1A - ctrl+z
Problem is fixed. I was sending message not as hex string but as binary, silly me :(
I've created balance checker for my openwrt routers. It is written in C and very simple. Works fine for velcom.by and mts.by.

To convert RGB 12 bit data to RGB 12 bit packed data

I have some RGB(image) data which is 12 bit. Each R,G,B has 12 bits, total 36 bits.
Now I need to club this 12 bit RGB data into a packed data format. I have tried to mention the packing as below:-
At present I have input data as -
B0 - 12 bits G0 - 12 bits R0 - 12 bits B1 - 12 bits G1 - 12 bits R1 - 12 bits .. so on.
I need to convert it to packed format as:-
Byte1 - B8 (8 bits of B0 data)
Byte2 - G4B4 (remaining 4 bits of B0 data+ first 4 bits of G0)
Byte3 - G8 (remaining 8 bits of G0)
Byte4 - R8 (first 8 bits of R0)
Byte5 - B4R4 (first 4 bits of B1 + last 4 bits of R0)
I have to write these individual bytes to a file in text format. one byte below another.
Similar thing i have to do for a 10 bit RGB input data.
Is there any tool/software to get the conversion of data i am looking to get done.
I am trying to do it in a C program - I am forming a 64 bit from the individual 12 bits of R,G,B (total 36 bits). But after that I am not able to come up with a logic to pick
the necessary bits from a R,G,B data to form a byte stream, and to dump them to a text file.
Any pointers will be helpful.
This is pretty much untested, super messy code I whipped together to give you a start. It's probably not packing the bytes exactly as you want, but you should get the general idea.
Apologies for the quick and nasty code, only had a couple of minutes, hope it's of some help anyway.
#include <stdio.h>
typedef struct
{
unsigned short B;
unsigned short G;
unsigned short R;
} UnpackedRGB;
UnpackedRGB test[] =
{
{0x0FFF, 0x000, 0x0EEE},
{0x000, 0x0FEF, 0xDEF},
{0xFED, 0xDED, 0xFED},
{0x111, 0x222, 0x333},
{0xA10, 0xB10, 0xC10}
};
UnpackedRGB buffer = {0, 0, 0};
int main(int argc, char** argv)
{
int numSourcePixels = sizeof(test)/sizeof(UnpackedRGB);
/* round up to the last byte */
int destbytes = ((numSourcePixels * 45)+5)/10;
unsigned char* dest = (unsigned char*)malloc(destbytes);
unsigned char* currentDestByte = dest;
UnpackedRGB *pixel1;
UnpackedRGB *pixel2;
int ixSource;
for (ixSource = 0; ixSource < numSourcePixels; ixSource += 2)
{
pixel1 = &test[ixSource];
pixel2 = ((ixSource + 1) < numSourcePixels ? &test[ixSource] : &buffer);
*currentDestByte++ = (0x0FF) & pixel1->B;
*currentDestByte++ = ((0xF00 & pixel1->B) >> 8) | (0x0F & pixel1->G);
*currentDestByte++ = ((0xFF0 & pixel1->G) >> 4);
*currentDestByte++ = (0x0FF & pixel1->R);
*currentDestByte++ = ((0xF00 & pixel1->R) >> 8) | (0x0F & pixel2->B);
if ((ixSource + 1) >= numSourcePixels)
{
break;
}
*currentDestByte++ = ((0xFF0 & pixel2->B) >> 4);
*currentDestByte++ = (0x0FF & pixel2->G);
*currentDestByte++ = ((0xF00 & pixel2->G) >> 8) | (0x0F & pixel2->R);
*currentDestByte++ = (0xFF0 & pixel2->R);
}
FILE* outfile = fopen("output.bin", "w");
fwrite(dest, 1, destbytes,outfile);
fclose(outfile);
}
Use bitwise & (and), | (or), and shift <<, >> operators.

Resources