This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
bwhodle's profile picture

How to merge bytes

Started by bwhodle, 09 July 2013 - 12:33 PM
bwhodle #1
Posted 09 July 2013 - 02:33 PM
My issue:

local byte1 = 255 --//11111111
local byte2 = 255 --//11111111
local byte3 = 255 --//11111111
local byte4 = 255 --//11111111
local merged = -//does something with byte1, byte2, byte3, and byte4 in order to merge them together and get 11111111111111111111111111111111 which is 4294967295
What I want to do is basically put 4 bytes together sequentially to get a 4-byte number. I need this to rewrite a security algorithm I once wrote in c# or some other cstyle language.
Like this: (note that this code is horrible and won't work at all but it has the general idea.

#include "stdafx.h"
#include <iostream>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
	char x = 0;	  
	char * x1 = &amp;x;
	char * x2 = (&amp;x + 1);
	char * x3 = (&amp;x + 2);
	char * x4 = (&amp;x + 3);
	*x1 = 255;
	*x2 = 255;
	*x3 = 255;
	*x4 = 255;
	int * result = (int *) &amp;x;
	cout << *result;
	return 0;
}
Obviously if you run the above on a computer, it'll corrupt the stack and blah blah blah. Basically

x1 = 0b11111111 #255
x2 = 0b11111111 #255
x3 = 0b11111111 #255
x4 = 0b11111111 #255
x5 = 0b11111111111111111111111111111111 #Big number
Basically making a 4-byte integer if you have the bytes you want it to be made of, in lua.
Lyqyd #2
Posted 09 July 2013 - 11:24 PM
Split into new topic.

Well, you could or them together at various amounts of left shift.
GopherAtl #3
Posted 10 July 2013 - 12:27 AM

local bytes={1,2,3,4}
local dword=0
for i=1,4 do
  dword=dword+bytes[i]*256^(i-1)
end
print(string.format("%x",dword)) --outputs "4030201"

alternately, with bit api,

local bytes={1,2,3,4}
local dword=0
for i=1,4 do
  dword=bit.bor(dword,bit.blshift(bytes[i],(i-1)*8))
end
print(string.format("%x",dword)) --outputs "4030201"