how to define byte array in Nemerle - nemerle

def cmd = array [ 0x0F, 0x03 ]
this code defines array of integers so I want array of bytes
interesting that
def cmd = array [ 0x0Fb, 0x03b ]
this code defines the same...
how to define byte array instead of int array here?

def cmd = array [ 0x0F : byte, 0x03 ]
and modifiers doesn't work for hex so far.

Related

Unpack byte array from BLE packet

Im developing an app using BLE where iPhone device is the peripheral, and will respond to write requests of type CBATTRequest from the Central.
My take is that this represents a byte array from value of CBATTRequest via request.value of type NSData that I can unpack to read packet # etc. Given the size (octets) and position of each field, how can I unpack and read each value, conceptually and technically?. And how would I go about constructing/packing this same byte array as if I was preparing to send this request? Since I will have to pack data in the same manner for the response.
When you receive the data, it's probably in a CBATTRequest. The data is contained in a member value of type NSData. The member length tells the length in bytes/octects.
CBATTRequest* request = ...;
NSData* value = request.value;
int packetLen = value.length;
It then makes sense to cast this to a struct that corresponds to the structure of the packet:
struct Packet {
unsgined char pktNo;
unsigned char ctrlCmd;
unsigned char txPowerRequest;
unsigned char uuid[2];
unsigned char txCnt;
unsigned char userPayload[14];
};
Packet* packet= (Packet)value.bytes;
Note that packet is of variable length. So only part of the userPayload is valid. The valid length is:
int userPayloadLength = packetLen - 6;
Now you can easily access the members:
int packetNumber = packet->pktNo;
To construct a similar packet, you would approach is slightly similarly.
Packet reponse;
response.pktNo = ...;
reponse.ctrlCmd = ...;
int userPayloadLength = 5;
NSData* value = [NSData dataWithBytes: &response length: userPayloadLength + 6];
Bit 4 to 0 set to 0x01 for..
This most likely is relative to a single octect, e.g. to ctrlCmd. To test it:
if (((packet->ctrlCmd >> 0) & 0x1f) == 0x01) ...
0x1f is the bit mask for 5 consecutive bits set (bit 0 to 5). >> 0 doesn't do anything but would be required if the bits were shifted, e.g. for bit 2 to 5 you would need to shift by 2.
A typical UUID is 16 bytes long. So I assume byte index 13 & 12 refers to bytes 12 and 13 within a 16 byte UUID (as only two bytes are transmitted). The remaining bytes are probably fixed to the base Bluetooth UUID:
00000000-0000-1000-8000-00805F9B34FB

How do I split a string given an array of split positions?

I'm using Ruby 2.4 and Rails 5. I have an array of indexes within a line
[5, 8, 10]
How do I take the above array, and a string, and form anotehr array of strings that are split by the above indexes? FOr instance, if the string is
abcdefghijklmn
and split it based ont eh above indexes, I would have an array with the following strings
abcde
fgh
ij
klmn
Try this
str = "abcdefghijklmn"
positions = [5, 8, 10]
parts = [0, *positions, str.size].each_cons(2).map { |a, b| str[a...b] }
# => ["abcde", "fgh", "ij", "klmn"]
Or,
If the positions are constant and known ahead of runtime (for example if they were the format for a phone number or credit card) just use a regexp
str.match(/(.....)(...)(..)(.*)/).captures
# => ["abcde", "fgh", "ij", "klmn"]
This will get the Job done
str = "abcdefghijklmn"
arr_1 = [5, 8, 10]
arr_2, prev = [], 0
(arr_1.length + 1).times do |x|
if arr_1[x] == nil then arr_1[x] = str.size end
arr_2 << str[prev..arr_1[x] -1]
prev = arr_1[x]
end
p arr_2
---------------------------------------
Program Run Output
["abcde", "fgh", "ij", "klmn"]
---------------------------------------
I hope this Helps

Read file text and store in array 2d

I have a file text "a.txt" :
1 2 3
4 5 6
7 8 9
Now i want store it in array 2d :
array ={ {1,2,3}{4,5,6}{7,8,9} }
I have try to :
array ={}
file = io.open("a.txt","r")
io.input(file)
i=0
for line in io.lines() do
array[i]=line
i=i+1
end
But it doesn't success.
Does anyone suggest me a way to do it?
You have some errors in your code. You first open the file a.txt and then set it for standard input. You don't need the open(). But i recommend to open the file and operate on it, using the lines() iterator on the file:
array = {}
file = io.open("a.txt","r")
i = 0
for line in file:lines() do
array[i]=line
i=i+1
end
Furthermore, with your method, you don't get the array you wished for ({ {1, 2, 3}, {4, 5, 6}, {7, 8, 9} }) but instead an array containing strings as elements:
{ "1 2 3", "4 5 6", "7 8 9" }.
To get the latter, you have to parse the string you have read. An easy way to do this is to use string.match with captures:
array ={}
file = io.open("a.txt","r")
for line in file:lines() do
-- extract exactly three integers:
local t = { string.match(line, "(%d+) (%d+) (%d+)")) }
table.insert(array, t) -- append row
end
See https://www.lua.org/manual/5.3/manual.html#pdf-string.match. For a arbitrary number of integers (or other numbers) on every line, you can use a loop together with string.gmatch():
array ={}
file = io.open("a.txt","r")
for line in file:lines() do
local t = {}
for num in string.gmatch(line, "(%d+)") do
table.insert(t, num)
end
table.insert(array, t)
end

IOS:Convert string to hexadecimal array

i have string representing data .i need to convert those data to the hex array .By using the hex array data i can pass it to the CRC for writing to the peripheral
My string data is like this
NSString *stringsdata=#"helloworld1234567812345q";
i need to convert to hex format array like
{0x0h,0x0e............0x0q}.
so by using this array i can keep the data in the crc and write it to the peripheral data as
Byte comm[24];
comm[0]=0x01;
comm[1]=0x30;
comm[2]=0x62;
comm[3]=0x00;................
have tried with many possible solutions but not luck.can any body help will be greatly appreciated.
A. The hexadecimal format is simply another representation of the same data.
B. You do not convert them into hex array. Every character has a number. For example in ASCII and UTF-8 the A has the number 65 (decimal representation). This is 0x41 in hex representation.
'A' (ASCII) == 65 == 0x41.
A hex number has the the digits 0-9, a-f, wherein a has the value of 10, b the value of 11 … It is converter into decimal representation by multiplying the upper digit by 16 and adding the lower digit. (0x41: 4 x 16 + 1 = 65.)
Please read and understand this: http://en.wikipedia.org/wiki/Hexadecimal
C. To convert a string into its number, you have to know, which code you want to apply. Probably you want to use UTF-8.
NSString *text = #"helloworld123123989128739";
NSUInteger length = [text lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
char data[length];
[text getCString:data maxLength:length usingEncoding:NSUTF8StringEncoding];
// Here we go
Byte[] class is an array of characters. I mean you can only set one character at it's index.
If we have
Byte comm[24]; then comm[0]=0x01; is looks like confusing here because it only saves one character.
And the statement will be like comm[0]='x';.
Below code will creates Byte[] from given string.
NSString *stringsdata=#"helloworld1234567812345q";
CFStringRef cfString = (__bridge CFStringRef)stringsdata;
char *array = charArrayFromCFStringRef(cfString);
size_t length= strlen(array);
Byte comm[24];
for (int i = 0; i < length; i++) {
comm[i] = array[i];
}
Conversion function:
char * charArrayFromCFStringRef(CFStringRef stringRef) {
if (stringRef == NULL) {
return NULL;
}
CFIndex length = CFStringGetLength(stringRef);
CFIndex maxSize = CFStringGetMaximumSizeForEncoding(length, kCFStringEncodingUTF8);
char *buffer = (char *)malloc(maxSize);
if (CFStringGetCString(stringRef, buffer, maxSize, kCFStringEncodingUTF8)) {
return buffer;
}
return NULL;
}
OutPut:
Printing description of comm:
(Byte [24]) comm = {
[0] = 'h'
[1] = 'e'
[2] = 'l'
[3] = 'l'
[4] = 'o'
[5] = 'w'
[6] = 'o'
[7] = 'r'
[8] = 'l'
[9] = 'd'
[10] = '1'
[11] = '2'
[12] = '3'
[13] = '4'
[14] = '5'
[15] = '6'
[16] = '7'
[17] = '8'
[18] = '1'
[19] = '2'
[20] = '3'
[21] = '4'
[22] = '5'
[23] = 'q'
}
The thing here is if you still convert any character from Byte[] then you can only save one character at any index.
Because for above characters it's hex value is more than one character and you can only save one character in Byte[].
I suggest to use NSArray to save each character's hex value in NSString format.

How to take in digits 0-255 from a file with no delimeters

I have a plaintext file that has only numerical digits in it (no spaces, commas, newlines, etc.) which contains n digits which range from 0 to 255. I want to take it in and store these values in an array.
Example
Let's say we have this sequence in the file:
581060100962552569
I want to take it in like this, where in.read is the file input stream, tempArray is a local array of at most 3 variables that is wiped every time something is stored in endArray, which is where I want the final values to go:
in.read tempArray endArray
5 [5][ ][ ] [] //It reads in "5", sees single-digit number X guarantees that "5X" is less than or equal to 255, and continues
8 [5][8][ ] [58] //It reads in "8", realizes that there's no number X that could make "58X" smaller than or equal to "255", so it stores "58" in endArray
1 [1][ ][ ] [58] //It wipes tempArray and reads the next value into it, repeating the logic of the first step
0 [1][0][ ] [58] //It realizes that all single-digit numbers X guarantee that "10X" is less than or equal to "255", so it continues
6 [1][0][6] [58][106] //It reads "6" and adds "106" to the endArray
0 [0][ ][ ] [58][106] //It wipes tempArray and stores the next value in it
1 [0][1][ ] [58][106]
0 [0][1][0] [58][106][10] //Even though all single-digit numbers X guarantee that "010X" is less than or equal to "255", tempArray is full, so it stores its contents in endArray as "10".
0 [0][ ][ ] [58][106][10]
9 [0][9][ ] [58][106][10]
6 [0][9][6] [58][106][10][96] //Not only can "96" not have another number appended to it, but tempArray is full
2 [2][ ][ ] [58][106][10][96]
5 [2][5][ ] [58][106][10][96] //There are numbers that can be appended to "25" to make a number less than or equal to "255", so continue
5 [2][5][5] [58][106][10][96][255] //"5" can be appended to "25" and still be less than or equal to "255", so it stores it in tempArray, finds tempArray is full, so it stores tempArray's values in endArray as "255"
2 [2][ ][ ] [58][106][10][96][255][37]
5 [2][5][ ] [58][106][10][96][255][37] //There are numbers that can be appended to "25" to make a number less than or equal to "255", so continue
6 [6][ ][ ] [58][106][10][96][255][37][25] //It sees that adding "6" to "25" would make a number that's larger than 255, so it stores "25" in the endArray and remembers "6" in the tempArray
9 [6][9][ ] [58][106][10][96][255][37][25][69] //It sees that there is no number X such that "69X" is less than "255", so it stores "69" in endArray
Does anyone know how I can accomplish this behavior? Please try to keep your answers in pseudocode, so it can be translated to many programming langauges
I would not use the temp array for holding the intermediate numbers - for the CPU numbers are stored in binary format and you are reading decimal numbers.
Something like this could solve your problem:
array = []
accumulator = 0
count = 0
while not EOF:
n = readDigit()
if accumulator*10 + n > 256 or count == 2:
array.push(accumulator)
accumulator = n
count = 0
else:
accumulator = accumulator*10 + n
count = count + 1
The results are appended to the array called array.
Edit: Thanks to DeanOC for noticing the missing counter. But DeanOC's solution initializes the counter for the first iteration to 0 instead of 1.
antiguru's response is nearly there.
The main problem is that it doesn't take into consideration that the numbers can only have 3 digits. This modification should work for you.
array = []
accumulator = 0
digitCounter = 0
while not EOF
n = readDigit()
if accumulator*10 + n > 255 or digitcounter = 3:
array.push(accumulator)
accumulator = n
digitCounter = 1
else:
accumulator = accumulator*10 + n
digitCounter = DigitCounter + 1

Resources