How to convert a binary number into integer in lua - lua

i have a array of 1 and 0,
for example 10110
values = {1,0,1,1,0}
max = 0
for value = 6,1,-1 do
max = max + 2*index*value
end
but how could get the index of the array in order to calculate the max

Try this:
values = {1,0,1,1,0}
max = 0
for index = 1,#values,1 do
max = max + 2^(#values-index)*values[index]
end
print(max)

Related

Displaying the bits values of a number in Wireshark Postdissector

I am writing a wireshark dissector of a custom protocol using LUA.For this custom protocol,there are no underlying TCP port or UDP port hence i have written a postdissector.
I am able to capture the payload from the below layers and convert it into a string.
local io_b = tostring(customprotocol)
After this, io_b has the following data
io_b = 10:10:10:10:01:0f:00:0d:00:00:00:00:01:00:00:00:00:20:0a:00:00
At first I split this string with : as the seperator and copy the elements into an array/table.
datafields = {}
index = 1
for value in string.gmatch(io_b, "[^:]+") do
datafields[index] = value
index = index + 1
end
Then I read each element of the datafield array as a uint8 value and check if a bit is set in that datafield element.How to make sure that each element of the table is uint8?
function lshift(x, by)
return x * 2 ^ by
end
--checks if a bit is set at a position
function IsBitSet( b, pos)
if b ~= nil then
return tostring(bit32.band(tonumber(b),lshift(1,pos)) ~= 0)
else
return "nil"
end
end
Then I want to display the value of each bit in the wireshark.I dont care about the first four bytes. The script displays each bit of the 5th byte(which is the 1st considered byte) correctly but displays all the bits value of the 6th byte and other remaining bytes as "nil".
local data_in_2 = subtree:add(customprotocol,"secondbyte")
data_in_2:add(firstbit,(IsBitSet((datafields[6]),7)))
data_in_2:add(secondbit,(IsBitSet((datafields[6]),6)))
data_in_2:add(thirdbit,(IsBitSet((datafields[6]),5)))
data_in_2:add(fourbit,(IsBitSet((datafields[6]),4)))
data_in_2:add(fivebit,(IsBitSet((datafields[6]),3)))
data_in_2:add(sixbit,(IsBitSet((datafields[6]),2)))
data_in_2:add(sevenbit,(IsBitSet((datafields[6]),1)))
data_in_2:add(eightbit,(IsBitSet((datafields[6]),0)))
What am i doing wrong?
Maybe i am wrong but it seems you can do it simpler with...
io_b = '10:10:10:10:01:0f:00:0d:00:00:00:00:01:00:00:00:00:20:0a:00:00'
-- Now replace all : on the fly with nothing and convert it with #Egor' comment tip
-- Simply by using string method gsub() from within io_b
b_num = tonumber(io_b:gsub('%:', ''), 16)
print(b_num)
-- Output: 537526272
#shakingwindow - I cant comment so i ask here...
Do you mean...
io_b = '10:10:10:10:01:0f:00:0d:00:00:00:00:01:00:00:00:00:20:0a:00:00'
-- Converting HEX to string - Replacing : with ,
io_hex = io_b:gsub('[%x]+', '"%1"'):gsub(':', ',')
-- Converting string to table
io_hex_tab = load('return {' .. io_hex .. '}')()
-- Put out key/value pairs by converting HEX value string to a number on the fly
for key, value in pairs(io_hex_tab) do
print(key, '=', tonumber(value, 16))
end
...that puts out...
1 = 16
2 = 16
3 = 16
4 = 16
5 = 1
6 = 15
7 = 0
8 = 13
9 = 0
10 = 0
11 = 0
12 = 0
13 = 1
14 = 0
15 = 0
16 = 0
17 = 0
18 = 32
19 = 10
20 = 0
21 = 0
...?

How to calculate the average of timestamps

I have a .log file that looks like this :
--hh:mm:ss
10:15:46
10:09:33
10:27:26
10:09:49
09:54:21
10:10:25
And what I need to do is to calculate the average on those timestamps, I wrote a function to calculate the average :
function calculate_average_working_hours(working_day_diff)
local current_hour, current_minutes, current_secondes = 0, 0, 0
local total_hour, total_minutes, total_secondes = 0, 0, 0
local working_days_counter = #working_day_diff
for key, value in pairs(working_day_diff) do
current_hour, current_minutes, current_secondes = extract_timestamp_value(value) --covert the values to numbers
total_hour = total_hour + current_hour
total_minutes = total_minutes + current_minutes
total_secondes = total_secondes + current_secondes
end
total_hour = math.ceil(total_hour / working_days_counter)
total_minutes = math.ceil(total_minutes / working_days_counter)
total_secondes = math.ceil(total_secondes / working_days_counter)
return ("%02d:%02d"):format(total_hour, total_minutes)
end
So basically what I'm doing is to sum the seconds, minutes, and hours and divide the results by the number of logs,
for example if i have 10:15:46 and 10:09:33 i will add the seconds, minutes and hours and divide it by 2
is this the correct way to calculate the average of timestamps values?
I would be something like this solved the problem:
--- example 1
local log = [[--hh:mm:ss
10:15:46
10:09:33
10:27:26
10:09:49
09:54:21
10:10:25
]]
local function seconds(v)
local h,m,s = v:match("(%d%d):(%d%d):(%d%d)")
if h and m and s then return h*3600+m*60+s else return nil end
end
local i,sum = 0, 0
for line in log:gmatch('(.-)[\r\n]') do
local r = seconds(line)
if r then i=i+1; sum = sum+r end
end
print(sum,i, os.date("!%X",sum/i) )

Convert string into array and do operations

I have a string like: "1234567334535674326774324423". I need to create a method to do the following:
Make an array consisting of digits in the string like [1, 2, 3, ..., 2, 3]
Sum all the odd positions of the array
Sum all the even positions of the array
Multiply the odd sum by 3
Sum step 4 and step 3.
Get the minimum number to sum to step 5 to get the sum that is a multiple of 5.
I don't know how to solve this with rails. If anyone can help me, I would be glad.
I have this:
barcode_array = #invoice.barcode.each_char.map {|c| c.to_i}
impares = [barcode_array[0]] + (1...barcode_array.size).step(2).collect { |i| barcode_array[i] }
pares = (2...barcode_array.size).step(2).collect { |i| barcode_array[i] }
suma_impares = impares.inject(:+)
mult_impares = suma_impares * 3
suma total = mult_impares + pares
I solved it. Here is the code if anyone needs it:
barcode_array = #invoice.barcode.each_char.map {|c| c.to_i}
impares = [barcode_array[0]] + (1...barcode_array.size).step(2).collect { |i| barcode_array[i] }
pares = (2...barcode_array.size).step(2).collect { |i| barcode_array[i] }
suma_impares = impares.inject(:+).to_i
mult_impares = suma_impares * 3
suma_pares = pares.inject(:+).to_i
suma_total = mult_impares + suma_pares
verificador = 10 - (suma_total - (suma_total / 10).to_i * 10)
#invoice.barcode = #invoice.barcode.to_s + verificador.to_s
I'm not sure what you mean in step 6, but here's how I would tackle 1-5:
s = '1234567334535674326774324423'
a = s.chars.map(&:to_i) # convert to an array of integers
odd_sum = 0
even_sum = 0
# sum up odds and evens
a.each_with_index {|n, i| n.even? ? even_sum += n : odd_sum += n}
total = even_sum + odd_sum * 3

I am trying to do arithmetic on table values and keep getting an error. here is my code

I am trying to perform arithmetic on table values and keep getting an error. Here is my total code. I am basically trying to generate simplex noise. I have created a multidimensional array (table) and am trying to perform operations on the values but i keep getting an error that says I cannot perform arithmetic on a table value. I don't know If I have to convert it to something or what. Please Help.
totalNoiseMap = {}
function simplex_noise(width, height)
simplexnoise = {}
for i = 1,512 do
simplexnoise[i] = {}
for j = 1, 512 do
simplexnoise[i][j] = 0
end
end
frequency = 5.0 / width
for x = 1, width do
for y = 1, height do
simplexnoise[x][y] = noise(x * frequency,y * frequency)
simplexnoise[x][y] = (simplexnoise[x][y] + 1) / 2
end
end
return simplexnoise
end
function noise(x, y, frequency)
return simplex_noise(x / frequency, y / frequency)
end
function generateOctavedSimplexNoise(width,height,octaves,roughness,scale)
totalnoise = {}
for i = 1,512 do
totalnoise[i] = {}
for j = 1, 512 do
totalnoise[i][j] = 0
end
end
layerFrequency = scale
layerWeight = 1
weightSum = 0
for octave = 1, octaves do
for x = 1, width do
for y = 1, height do
totalnoise[x][y] = (totalnoise[x][y] + noise(x * layerFrequency,y * layerFrequency, 2) * layerWeight)
end
end
--Increase variables with each incrementing octave
layerFrequency = layerFrequency * 2
weightSum = weightSum + layerWeight
layerWeight = layerWeight * roughness
end
return totalnoise
end
totalNoiseMap = generateOctavedSimplexNoise(512, 512, 3, 0.4, 0.005)
totalnoise[x][y] + noise(x * layerFrequency,y * layerFrequency, 2) * layerWeight
Here you get table noise(x * layerFrequency,y * layerFrequency, 2), mult it by scalar layerWeight and than add it to scalar totalnoise[x][y].
I can think of how to multiply table by scalar - it should be something like
for i = 1,512 do
for j = 1,512 do
a[i][j] = t[i][j] * scalar
end
end
But I'm unable to get what you're trying to do by adding. Suppose it should be addition of two tables
for i = 1,512 do
for j = 1,512 do
a[i][j] = b[i][j] + c[i][j]
end
end
But it works only with same-sized tables

Lua integer won't increment

I have this simple lua function designed to solve the problem of consecutive prime sum.
The prime 41, can be written as the sum of six consecutive primes:
41 = 2 + 3 + 5 + 7 + 11 + 13
This is the longest sum of consecutive primes that adds to a prime below one-hundred.
this is my function:
function numOfConsecPrimes(limit)
a = allPrimes(limit/2)
length = table.getn(a)
sumSoFar = 0 innerSum = 0 finalSum = 0
pos = 1
items = 0 innerItems = 0 finalItems = 0
resetpos = pos
while resetpos < length do
pos = resetpos
resetpos = resetpos + 1
items = 0
sumSoFar = 0
while sumSoFar < limit and pos < length do
if isPrime(sumSoFar) == true then innerSum = sumSoFar innerItems = items end
print(sumSoFar)
sumSofar = sumSoFar + a[pos]
print(a[pos] .."->"..sumSoFar)
pos = pos + 1
items = items + 1
end
if innerItems > finalItems then finalItems = innerItems finalSum = innerSum end
end
end
But for some reason, sumSoFar just won't change. I'm printing it before and after the addition of a[pos] and it stays zero always. I'm printing a[pos] as you see and the values are fine. So what's going on?
If this is your exact code then you simply have a typo.
sumSofar = sumSoFar + a[pos]
Capitalize the f in the first sumSofar so it matches all the other ones.

Resources