i get run time error while submitting my answer while submitting on leetcode. it running successfully and all test cases are correct - queue

class MyCircularQueue {
private:
int * arr;
int front;
int rear;
int size;
public:
MyCircularQueue(int k) {
size = k;
arr = new int [size];
front = rear = -1;
}
bool enQueue(int value) {
if(front == 0 && rear == size-1 || rear == (front-1)%(size-1)){
// cout << "queue is full";
return false;
}
else if(front == -1){
rear = front = 0;
}
else if(rear == size-1 && front != 0){
rear = 0;
}
else{
rear++;
}
arr[rear]= value;
return true;
}
bool deQueue() {
int ans = arr[front];
if(front == -1){
// cout << "queue is Empty ";
return -1;
}
else if(front == rear){
front = rear = -1;
}
else if(front == size-1){
front = 0;
}
else{
front++;
}
return ans;
}
int Front() {
if(front == -1){
return -1;
}
else{
return arr[front];
}
}
int Rear() {
if(front == -1){
return -1;
}
else{
return arr[rear];
}
}
bool isEmpty() {
if(front == -1){
return -1;
}
else{
return 1;
}
}
bool isFull() {
if(front == 0 && rear == size-1 || rear == (front-1)%(size-1)){
return 1;
}
else {
return -1;
}
}
};
run time error.
=================================================================
==34==ERROR: AddressSanitizer: heap-buffer-overflow on address 0x60300000057c at pc 0x00000034b71d bp 0x7ffc594a39b0 sp 0x7ffc594a39a8
READ of size 4 at 0x60300000057c thread T0
#4 0x7f8aefa020b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
0x60300000057c is located 4 bytes to the left of 24-byte region [0x603000000580,0x603000000598)
allocated by thread T0 here:
#4 0x7f8aefa020b2 (/lib/x86_64-linux-gnu/libc.so.6+0x270b2)
Shadow bytes around the buggy address:
0x0c067fff8050: fd fd fd fd fa fa fd fd fd fd fa fa fd fd fd fd
0x0c067fff8060: fa fa fd fd fd fd fa fa fd fd fd fa fa fa fd fd
0x0c067fff8070: fd fd fa fa fd fd fd fa fa fa fd fd fd fd fa fa
0x0c067fff8080: fd fd fd fd fa fa fd fd fd fa fa fa 00 00 00 00
0x0c067fff8090: fa fa fd fd fd fd fa fa 00 00 00 00 fa fa fd fd
=>0x0c067fff80a0: fd fd fa fa 00 00 00 00 fa fa 00 00 00 fa fa[fa]
0x0c067fff80b0: 00 00 00 fa fa fa fd fd fd fd fa fa fa fa fa fa
0x0c067fff80c0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff80d0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff80e0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
0x0c067fff80f0: fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa fa
Shadow byte legend (one shadow byte represents 8 application bytes):
Addressable: 00
Partially addressable: 01 02 03 04 05 06 07
Heap left redzone: fa
Freed heap region: fd
Stack left redzone: f1
Stack mid redzone: f2
Stack right redzone: f3
Stack after return: f5
Stack use after scope: f8
Global redzone: f9
Global init order: f6
Poisoned by user: f7
Container overflow: fc
Array cookie: ac
Intra object redzone: bb
ASan internal: fe
Left alloca redzone: ca
Right alloca redzone: cb
Shadow gap: cc
==34==ABORTING
the above code is successfully running, but while submitting i get runtime error.

Related

AutoHotkey - limiting the number and type of characters taken from the string

I have an ahk script for an IRC client which after entering nick!ident#host into the text field and pressing F4 decrypts the ident which is the encrypted form of the IP address:
F4::
Clipboard =
Send ^a^x
ClipWait, 0
If ErrorLevel
MsgBox, 48, Error, An error occurred while waiting for the clipboard. Aborting.
Else Clipboard := decode(SubStr(Clipboard, -15, -8))
Return
decode(str) {
Static code := " " "
( LTrim Join`s
00 0x 02 03 04 0z 06 01 08 09 0B 0b 0c 0d 0e 0H x0 xx x2 x3 x4 xz x6 x1 x8 x9 xB xb xc xd xe xH 20 2x
22 23 24 2z 26 21 28 29 2B 2b 2c 2d 2e 2H 30 3x 32 33 34 3z 36 31 38 39 3B 3b 3c 3d 3e 3H 40 4x 42 43
44 4z 46 41 48 49 4B 4b 4c 4d 4e 4H z0 zx z2 z3 z4 zz z6 z1 z8 z9 zB zb zc zd ze zH 60 6x 62 63 64 6z
66 61 68 69 6B 6b 6c 6d 6e 6H 10 1x 12 13 14 1z 16 11 18 19 1B 1b 1c 1d 1e 1H 80 8x 82 83 84 8z 86 81
88 89 8B 8b 8c 8d 8e 8H 90 9x 92 93 94 9z 96 91 98 99 9B 9b 9c 9d 9e 9H B0 Bx B2 B3 B4 Bz B6 B1 B8 B9
BB Bb Bc Bd Be BH b0 bx b2 b3 b4 bz b6 b1 b8 b9 bB bb bc bd be bH c0 cx c2 c3 c4 cz c6 c1 c8 c9 cB cb
cc cd ce cH d0 dx d2 d3 d4 dz d6 d1 d8 d9 dB db dc dd de dH e0 ex e2 e3 e4 ez e6 e1 e8 e9 eB eb ec ed
ee eH H0 Hx H2 H3 H4 Hz H6 H1 H8 H9 HB Hb Hc Hd He HH
)"
Loop, % StrLen(str) / 2
new .= "." Round((Instr(code, " " SubStr(str, 2 * A_Index - 1, 2), True) - 1) / 3)
Return SubStr(new, 2)
}
Decryption is performed according to the following key:
https://pastebin.com/raw/P8cQtH2v
For example, for user data asdf!~z3040d4B#webchat will decrypt the ident from z3040d4B as 83.4.13.75 and copies this value to the clipboard.
But there are cases when the encoded form of the IP (ident) is longer or shorter than 8 characters or contains characters that aren't in the decryption key. Then it's impossible to decode the IP correctly. So I would like the script to copy the decryption result to the clipboard only if the retrieved string (between ! and #, omitting the ~ sign if present) is 8 characters long and contains the characters contained in the key I entered. Otherwise, the script should clear the clipboard. How to do it?
A regex match approach with e.g the regex !~?[A-z\d]{8}# is surely most convenient:
F4::
Clipboard := ""
SendInput, ^a^x
ClipWait, 0
if (ErrorLevel)
MsgBox, 48, Error, An error occurred while waiting for the clipboard. Aborting.
else if (Clipboard ~= "!~?[A-z\d]{8}#")
Clipboard := decode(SubStr(Clipboard, -15, -8))
else
Clipboard := ""
Return
decode(str)
{
static code := " " "
( LTrim Join`s
00 0x 02 03 04 0z 06 01 08 09 0B 0b 0c 0d 0e 0H x0 xx x2 x3 x4 xz x6 x1 x8 x9 xB xb xc xd xe xH 20 2x
22 23 24 2z 26 21 28 29 2B 2b 2c 2d 2e 2H 30 3x 32 33 34 3z 36 31 38 39 3B 3b 3c 3d 3e 3H 40 4x 42 43
44 4z 46 41 48 49 4B 4b 4c 4d 4e 4H z0 zx z2 z3 z4 zz z6 z1 z8 z9 zB zb zc zd ze zH 60 6x 62 63 64 6z
66 61 68 69 6B 6b 6c 6d 6e 6H 10 1x 12 13 14 1z 16 11 18 19 1B 1b 1c 1d 1e 1H 80 8x 82 83 84 8z 86 81
88 89 8B 8b 8c 8d 8e 8H 90 9x 92 93 94 9z 96 91 98 99 9B 9b 9c 9d 9e 9H B0 Bx B2 B3 B4 Bz B6 B1 B8 B9
BB Bb Bc Bd Be BH b0 bx b2 b3 b4 bz b6 b1 b8 b9 bB bb bc bd be bH c0 cx c2 c3 c4 cz c6 c1 c8 c9 cB cb
cc cd ce cH d0 dx d2 d3 d4 dz d6 d1 d8 d9 dB db dc dd de dH e0 ex e2 e3 e4 ez e6 e1 e8 e9 eB eb ec ed
ee eH H0 Hx H2 H3 H4 Hz H6 H1 H8 H9 HB Hb Hc Hd He HH
)"
Loop, % StrLen(str) / 2
{
if (!InStr(code, block := " " SubStr(str, 2 * A_Index - 1, 2), true))
return ""
new .= "." Round((InStr(code, block, true) - 1) / 3)
}
return SubStr(new, 2)
}
~=(docs) is the RegExMatch()(docs) shorthand.

Inline stack frames with IDebugControl5.GetContextStackTraceEx?

How can I resolve the symbols of a DEBUG_STACK_FRAME_EX with inline frames?
I am aware of DEBUG_STACK_FRAME_EX and its ULONG InlineFrameContext, but I don't understand how to resolve the InlineFrameContext to the corresponding symbol.
And what is the FrameSignature and FrameId in INLINE_FRAME_CONTEXT?
InLineFrameContext is an union only FrameType is Defined which is the second byte in the ContextValue DWORD
this normally would be 25ed0200 for an inline frame (most of the times i noticed though it can be b5b80200 too in some system dll's inline frames
the output is same as kvf and .inline 1 (.inline enable )
if you disable inline
the InlineFrameContext would be 0xffffffff
where ff is STACK_FRAME_TYPE_IGNORE
25ed / b5b8 , ffff , etc The Frame Signature and the 00 FrameID
are fetched from symbols
(if you really want to know look into the dia sdk com sorcery which loads the symbols and fetches this signature from pdb ( dbghelp!g+0xxxx (2360 in win10 dbghelp.dll) )
whatever they are they don't appear to be useful for any co-relation with symbols and the signature varies on each invocation or windbg session
and iirc on every .reload /f
even the OutputContextStackTraceEx function doesn't seem to use the signature and Id (type is used to denote inline if type was 02 )
if you want to experiment you can check this code (its an engextcpp extension so you compile and load it in windbg and run the command it will
print the stack along with some spew exactly as if you issued kvf
#include <codeanalysis\warnings.h>
#pragma warning( push )
#pragma warning ( disable : ALL_CODE_ANALYSIS_WARNINGS )
#include <engextcpp.cpp>
#pragma warning( pop )
class EXT_CLASS : public ExtExtension {
public:
EXT_COMMAND_METHOD(gcsex);
};
EXT_DECLARE_GLOBALS();
ULONG64 InstructionOffset; DEBUG_STACK_FRAME ScopeFrame; CONTEXT ScopeContext;
DEBUG_STACK_FRAME_EX FrameEx[0x20];CONTEXT FrameContext[0x20];ULONG FramesFilled;
INLINE_FRAME_CONTEXT Inlineframectx;
EXT_COMMAND( gcsex, "", "" ) {
InstructionOffset = NULL; FramesFilled = NULL;
memset(&ScopeFrame,0,sizeof(ScopeFrame));memset(&ScopeContext,0,sizeof(ScopeContext));
memset(&FrameEx, 0, sizeof(FrameEx)); memset(&FrameContext,0,sizeof(FrameContext));
memset(&Inlineframectx,0,sizeof(Inlineframectx));
m_Symbols->GetScope(&InstructionOffset,&ScopeFrame,&ScopeContext,sizeof(ScopeContext));
Out("%I64X%I64x %X\n",InstructionOffset,ScopeFrame.InstructionOffset,ScopeContext.Eip);
m_Control5->GetContextStackTraceEx( &ScopeContext,sizeof(ScopeContext),
FrameEx,0x20,FrameContext,0x20*sizeof(CONTEXT),sizeof(CONTEXT),&FramesFilled );
Out("Frames Filled = %x\n" , FramesFilled);
for(ULONG i = 0 ; i < FramesFilled; i++) {
Inlineframectx.ContextValue = FrameEx[i].InlineFrameContext;
Out("Inline Frame Context for frame %d=%x\n" , i , FrameEx[i].InlineFrameContext);
Out("Frameid = %x FrameType = %x Frame Signature = %x\n" ,
Inlineframectx.FrameId , Inlineframectx.FrameType , Inlineframectx.FrameSignature);
}
m_Control5->OutputContextStackTraceEx ( DEBUG_OUTCTL_ALL_CLIENTS,FrameEx,FramesFilled,
&FrameContext,FramesFilled*sizeof(CONTEXT),sizeof(CONTEXT),0x1fff );
}
you should see some thing like this on executing the extension
0:000> kb
# ChildEBP RetAddr Args to Child
00 (Inline) -------- -------- -------- -------- runasm!helper [e:\test\runasm\runasm.cpp # 4]
01 0029fd44 0124159a 00000001 0008c5f0 00091a70 runasm!main+0x20 [e:\test\runasm\runasm.cpp # 32]
02 (Inline) -------- -------- -------- -------- runasm!invoke_main+0x1d [f:\dd\vctools\crt\vcstartup\src\startup\exe_common.inl # 74]
03 0029fd90 75d53c45 7ffdf000 0029fddc 778037f5 runasm!__scrt_common_main_seh+0xff [f:\dd\vctools\crt\vcstartup\src\startup\exe_common.inl # 264]
04 0029fd9c 778037f5 7ffdf000 75826e8f 00000000 kernel32!BaseThreadInitThunk+0xe
05 0029fddc 778037c8 01241652 7ffdf000 00000000 ntdll!__RtlUserThreadStart+0x70
06 0029fdf4 00000000 01241652 7ffdf000 00000000 ntdll!_RtlUserThreadStart+0x1b
0:000> !gcsex
12412F0 12412f0 12412F0
Frames Filled = 7
Inline Frame Context = for frame 0 = 25ed0200
Frameid = 0 FrameType = 2 Frame Signature = 25ed
Inline Frame Context = for frame 1 = 25ed0100
Frameid = 0 FrameType = 1 Frame Signature = 25ed
Inline Frame Context = for frame 2 = 25ed8200
Frameid = 0 FrameType = 82 Frame Signature = 25ed
Inline Frame Context = for frame 3 = 25ed8100
Frameid = 0 FrameType = 81 Frame Signature = 25ed
Inline Frame Context = for frame 4 = 25ed8100
Frameid = 0 FrameType = 81 Frame Signature = 25ed
Inline Frame Context = for frame 5 = 25ed8100
Frameid = 0 FrameType = 81 Frame Signature = 25ed
Inline Frame Context = for frame 6 = 25ed8100
Frameid = 0 FrameType = 81 Frame Signature = 25ed
# Memory ChildEBP RetAddr Args to Child
00 (Inline) -------- -------- -------- -------- runasm!helper (Inline Function # 012412f0) (CONV: cdecl) [e:\test\runasm\runasm.cpp # 4]
01 0029fd44 0124159a 00000001 0008c5f0 00091a70 runasm!main(void)+0x20 (FPO: [0,1,4]) (CONV: cdecl) [e:\test\runasm\runasm.cpp # 32]
02 4c (Inline) -------- -------- -------- -------- runasm!invoke_main+0x1d (Inline Function # 0124159a) (CONV: cdecl) [f:\dd\vctools\crt\vcstartup\src\startup\exe_common.inl # 74]
03 0 0029fd90 75d53c45 7ffdf000 0029fddc 778037f5 runasm!__scrt_common_main_seh(void)+0xff (FPO: [Non-Fpo]) (CONV: cdecl) [f:\dd\vctools\crt\vcstartup\src\startup\exe_common.inl # 264]
04 c 0029fd9c 778037f5 7ffdf000 75826e8f 00000000 kernel32!BaseThreadInitThunk+0xe (FPO: [Non-Fpo])
05 40 0029fddc 778037c8 01241652 7ffdf000 00000000 ntdll!__RtlUserThreadStart+0x70 (FPO: [Non-Fpo])
06 18 0029fdf4 00000000 01241652 7ffdf000 00000000 ntdll!_RtlUserThreadStart+0x1b (FPO: [Non-Fpo])
0:000> .inline
Include inline function queries is "enabled".
0:000> .inline 0
Include inline function queries is "disabled".
0:000> kb
# ChildEBP RetAddr Args to Child
00 0029fd44 0124159a 00000001 0008c5f0 00091a70 runasm!main+0x20 [e:\test\runasm\runasm.cpp # 32]
01 0029fd90 75d53c45 7ffdf000 0029fddc 778037f5 runasm!__scrt_common_main_seh+0xff [f:\dd\vctools\crt\vcstartup\src\startup\exe_common.inl # 264]
02 0029fd9c 778037f5 7ffdf000 75826e8f 00000000 kernel32!BaseThreadInitThunk+0xe
03 0029fddc 778037c8 01241652 7ffdf000 00000000 ntdll!__RtlUserThreadStart+0x70
04 0029fdf4 00000000 01241652 7ffdf000 00000000 ntdll!_RtlUserThreadStart+0x1b
0:000> !gcsex
12412F0 12412f0 12412F0
Frames Filled = 5
Inline Frame Context = for frame 0 = ffffffff
Frameid = ff FrameType = ff Frame Signature = ffff
Inline Frame Context = for frame 1 = ffffffff
Frameid = ff FrameType = ff Frame Signature = ffff
Inline Frame Context = for frame 2 = ffffffff
Frameid = ff FrameType = ff Frame Signature = ffff
Inline Frame Context = for frame 3 = ffffffff
Frameid = ff FrameType = ff Frame Signature = ffff
Inline Frame Context = for frame 4 = ffffffff
Frameid = ff FrameType = ff Frame Signature = ffff
# Memory ChildEBP RetAddr Args to Child
00 0029fd44 0124159a 00000001 0008c5f0 00091a70 runasm!main(void)+0x20 (FPO: [0,1,4]) (CONV: cdecl) [e:\test\runasm\runasm.cpp # 32]
01 4c 0029fd90 75d53c45 7ffdf000 0029fddc 778037f5 runasm!__scrt_common_main_seh(void)+0xff (FPO: [Non-Fpo]) (CONV: cdecl) [f:\dd\vctools\crt\vcstartup\src\startup\exe_common.inl # 264]
02 c 0029fd9c 778037f5 7ffdf000 75826e8f 00000000 kernel32!BaseThreadInitThunk+0xe (FPO: [Non-Fpo])
03 40 0029fddc 778037c8 01241652 7ffdf000 00000000 ntdll!__RtlUserThreadStart+0x70 (FPO: [Non-Fpo])
04 18 0029fdf4 00000000 01241652 7ffdf000 00000000 ntdll!_RtlUserThreadStart+0x1b (FPO: [Non-Fpo])
results to corroborate the edit that the Signature varies per session
cdb -c "$$>a< gcsex.txt" runasm.exe | grep -i Sign
Frameid = 0 FrameType = 1 Frame Signature = 1e7e
Frameid = 0 FrameType = 82 Frame Signature = 1e7e
Frameid = 0 FrameType = 81 Frame Signature = 1e7e
Frameid = 0 FrameType = 81 Frame Signature = 1e7e
Frameid = 0 FrameType = 81 Frame Signature = 1e7e
Frameid = 0 FrameType = 81 Frame Signature = 1e7e
cdb -c "$$>a< gcsex.txt" runasm.exe | grep -i Sign
Frameid = 0 FrameType = 1 Frame Signature = b649
Frameid = 0 FrameType = 82 Frame Signature = b649
Frameid = 0 FrameType = 81 Frame Signature = b649
Frameid = 0 FrameType = 81 Frame Signature = b649
Frameid = 0 FrameType = 81 Frame Signature = b649
Frameid = 0 FrameType = 81 Frame Signature = b649
cdb -c "$$>a< gcsex.txt" runasm.exe | grep -i Sign
Frameid = 0 FrameType = 1 Frame Signature = decf
Frameid = 0 FrameType = 82 Frame Signature = decf
Frameid = 0 FrameType = 81 Frame Signature = decf
Frameid = 0 FrameType = 81 Frame Signature = decf
Frameid = 0 FrameType = 81 Frame Signature = decf
Frameid = 0 FrameType = 81 Frame Signature = decf
cat gcsex.txt
.load gcsex
bp runasm!main "!gcsex;q"
g
This is using some wrappers, but the intention should be clear.
Using IDebugSymbols4::GetNameByInlineContext if the InlineFrameContext indicates that it is an inline frame, and IDebugSymbols4::GetSymbolNameByOffset otherwise.
C# example below:
ulong displacement;
var builder = new StringBuilder(256);
var isInlineFrame = frame.InlineFrameContext.FrameType.HasFlag(StackFrameType.Inline);
if (isInlineFrame)
{
_symbols5.GetNameByInlineContext(frame.InstructionOffset, frame.InlineFrameContext.ContextValue, ref builder, out displacement);
}
else {
_symbols5.GetSymbolNameByOffset(frame.InstructionOffset, ref builder, out displacement);
}
var name = builder.ToString();

HMAC implementation failure

I hope this is the right forum; I was not sure if I should ask this in stackoverflow, cryptography or security.
So my problem is that php's hash_hmac function is only available with php >=5.1.2. Because some servers are not updated to this version I wrote my own HMAC-implementaion based on php's hash function. But the code doesn't produce the same output as hash_hmac...
So where is my mistake?
define("HASH_ALGO", "sha512");
define("HMAC_BLOCKSIZE", 64);
function computeHMAC($message, $key) {
$ikey;
$okey;
$zero = hex2bin("00");
$ipad = hex2bin("36");
$opad = hex2bin("5C");
/*
* HMAC construction scheme:
* $ikey = $key padded with zeroes to blocksize and then each byte xored with 0x36
* $okey = $key padded with zeroes to blocksize and then each byte xored with 0x5C
* hash($okey . hash($ikey . $message))
*/
//Hash key if it is larger than HMAC_BLOCKSIZE
if (strlen($key) > HMAC_BLOCKSIZE) {
$key = hash(HASH_ALGO, $key, true);
}
//Fill ikey with zeroes
for ($i = 0; $i < HMAC_BLOCKSIZE; $i++) {
$ikey[$i] = $zero;
}
//Fill ikey with the real key
for ($i = 0; $i < strlen($key); $i++) {
$ikey[$i] = $key[$i];
}
//Until they get xored both keys are equal
$okey = $ikey;
//Xor both keys
for ($i = 0; $i < HMAC_BLOCKSIZE; $i++) {
$ikey[$i] ^= $ipad;
$okey[$i] ^= $opad;
}
//Build inner hash
$innerHash = hash(HASH_ALGO, $ikey . $message, true);
//Build outer hash
$outerHash = hash(HASH_ALGO, $okey . $innerHash, true);
return $outerHash;
}
The function was tested with the following code:
echo hexDump(computeHMAC("Testolope", "Testkeyolope"));
echo hexDump(hash_hmac(HASH_ALGO, "Testolope", "Testkeyolope", true));
The output is the following:
HexDump (64 Bytes):
65 a8 81 af 49 f2 49 c5 64 7a 7a b7 a6 ac a0 4e 9e 9b 1a 3c 76 fc 48 19 13 33 e0 f8 82 be 48 52 1a 50 49 09 1e fe bf 94 63 5f 9d 36 82 3f 2f a1 43 b4 60 9f 9f e5 d1 64 c6 5b 32 22 45 07 c9 cb
HexDump (64 Bytes):
d2 e9 52 d2 ab f0 db a7 60 e0 52 b0 5c 23 5a 73 d9 8c 78 8e 9e fb 26 82 54 7e f9 c8 f1 65 df 7f 97 44 fe 2b 1e 2b 6d d5 cb a4 ba c6 73 35 06 9c 0f c8 2d 36 8c b3 9b c4 48 01 5c c2 9f ce b4 08
The problem is that you've mixed up the digest size and block size; SHA-512 has a digest size of 64, but a block size of 128.
Secondly, both $ikey and $okey are arrays and not strings, so you need to convert them both into a string first:
$innerHash = hash(HASH_ALGO, join($ikey) . $message, true);
$outerHash = hash(HASH_ALGO, join($okey) . $innerHash, true);
That said, both hash() and hash_hmac() are documented as being available since 5.1.2, so I'm not sure what this will achieve :)

Hexadecimal data processing in Matlab

I have a string of Hex data streaming out as my data, it looks like this:
"00 E1 08 A2 05 FF"
I need them concatenated and then converted to decimal in column format, something like this:
00E1
08A2
05FF
Finally after conversion to decimal:
225
2210
1535
Total data available is 70,000.
Anyone can help me? I'm a newbie in Matlab, I tried writing the following code but no luck.
N=140000; %N is the number of data
n=N/2; %n is the number of concatenated data
filename=input('\nFile-name: ','s');
data_import=importdata(filename,' ', 1);
data_char=char(data_import);
data_str=sscanf(data_char, '%s', [N,1]);
data_out=textscan(data_str, '%4c',n);
importdata based approach -
data_import = importdata(filename,'')
C = regexp(data_import,' ','Split')
C1 = C{:}
t1 = reshape(C1(~cellfun(#isempty,C1)),2,[]).' %//'
data_out = hex2dec([char(t1(:,1)) char(t1(:,2))])
Alternative textscan based approach -
fileID = fopen(filename);
data_import = textscan(fileID,'%s')
fclose(fileID);
t1 = reshape(data_import{:}.',2,[]).'
data_out = hex2dec([char(t1(:,1)) char(t1(:,2))])
filename=input('\nFile-name: ','s');
data_import=importdata(filename,' ', 1);
data_char=char(data_import);
data_str=sscanf(data_char, '%s', [N,1]);
data_out = [];
for i=1:4:N
a = data_str(i:i+4);
d = hex2dec(a);
data_out = [data_out;d];
end
Hope this helps..
Edit:
Example String: 00 D5 00 CE 00 C7 00 C0 00 B9 00 D5 00 CE 00 C7 00 C0 00 B9 00 D5 00 CE 00 C7 00 C0 00 B9
Code:
data = '00 D5 00 CE 00 C7 00 C0 00 B9 00 D5 00 CE 00 C7 00 C0 00 B9 00 D5 00 CE 00 C7 00 C0 00 B9';
a = regexprep(num2str(data,17), '\s', '');
sizeOfA = size(a,2);
data_out = [];
for i = 1:4:sizeOfA
a1 = a(i:i+3);
d = hex2dec(a1);
data_out = [data_out;d];
end

Functions to deal with Unicode string manipulation with PowerBuilder 12.1

I am currently working on converting our PowerBuilder 12.1 application, which does not currently support Unicode, into a Unicode supporting application.
I have made some modifications to save Unicode data to our database, as well to files, but I have hit a slight snag in processing strings.
For example, the character 𠆾 is a Surrogate Pair and PowerBuilder interprets this as 2 characters (similar to how .NET operates). Thus:
LEN("𠆾") = 2
To me, this part makes sense, as it is count each code unit as a character.
Currently we have come up with two solutions to handle doing string functions with Unicode characters:
Callable OLEObjects written in C# .NET
using the PBNI interface to call C# .NET (want to stay away from this solution if possible)
An example of the .NET code we are thinking of using for determining the string length is:
StringInfo.ParseCombiningCharacters("𠆾").Length = 1
We are just worried about the impact on performance with constantly calling the OLEObjects/PBNI to do all of our string processing. Have any of the other PowerBuilder developers here done Unicode string manipulation (LEN, MID, POS, etc), and how did you do it?
Thank you.
This is in response to Seki's hex conversion function. I'm posting it as an answer so I can include source code. I use the Microsoft cryptographic functions to display blobs in my debugging tools. Here's a simplified version of my blob window. The one I use is PFC-based and uses an object that wraps the MS Crypto library. It's from PB 12.5 but should import into any Unicode version of PB.
HA$PBExportHeader$w_show_blob.srw
forward
global type w_show_blob from window
end type
type sle_1 from singlelineedit within w_show_blob
end type
type mle_1 from multilineedit within w_show_blob
end type
end forward
global type w_show_blob from window
integer width = 3081
integer height = 1988
boolean titlebar = true
boolean controlmenu = true
boolean minbox = true
boolean maxbox = true
boolean resizable = true
boolean center = true
sle_1 sle_1
mle_1 mle_1
end type
global w_show_blob w_show_blob
type prototypes
FUNCTION boolean CryptBinaryToString ( &
Blob pbBinary, &
ulong cbBinary, &
ulong dwFlags, &
Ref string pszString, &
Ref ulong pcchString ) &
LIBRARY "crypt32.dll" ALIAS FOR "CryptBinaryToStringW"
end prototypes
type variables
CONSTANT Ulong CRYPT_STRING_HEXASCIIADDR = 11
end variables
forward prototypes
public subroutine of_showblob (ref blob abl_data)
end prototypes
public subroutine of_showblob (ref blob abl_data);unsignedlong lul_size, lul_bufsize
string ls_hex
try
lul_size = len(abl_data)
sle_1.text = string(lul_size)
setnull(ls_hex)
cryptbinarytostring( abl_data, lul_size, CRYPT_STRING_HEXASCIIADDR, ls_hex, lul_bufsize)
ls_hex = space(lul_bufsize)
if not cryptbinarytostring( abl_data, lul_size, CRYPT_STRING_HEXASCIIADDR , ls_hex, lul_bufsize) then
mle_1.text = "error converting blob data"
else
mle_1.text = ls_hex
end if
catch(runtimeerror re)
messagebox("oops", re.text)
end try
end subroutine
on w_show_blob.create
this.sle_1=create sle_1
this.mle_1=create mle_1
this.Control[]={this.sle_1,&
this.mle_1}
end on
on w_show_blob.destroy
destroy(this.sle_1)
destroy(this.mle_1)
end on
type sle_1 from singlelineedit within w_show_blob
integer x = 73
integer width = 517
integer height = 88
integer taborder = 10
integer textsize = -10
integer weight = 400
fontcharset fontcharset = ansi!
fontpitch fontpitch = variable!
fontfamily fontfamily = swiss!
string facename = "Arial"
long textcolor = 33554432
long backcolor = 553648127
string text = "none"
boolean displayonly = true
borderstyle borderstyle = stylelowered!
end type
type mle_1 from multilineedit within w_show_blob
integer x = 64
integer y = 96
integer width = 2898
integer height = 1716
integer taborder = 10
integer textsize = -10
integer weight = 400
fontcharset fontcharset = ansi!
fontpitch fontpitch = fixed!
fontfamily fontfamily = modern!
string facename = "Courier New"
long textcolor = 33554432
string text = "none"
boolean hscrollbar = true
boolean vscrollbar = true
boolean displayonly = true
borderstyle borderstyle = stylelowered!
end type
To use it, assuming your blob is lbl_myBlob:
open(w_show_blob)
w_show_blob.of_showblob(lbl_myBlob)
The output in the MLE looks like this:
0000 42 4d ee 00 00 00 00 00 00 00 76 00 00 00 28 00 BM........v...(.
0010 00 00 10 00 00 00 0f 00 00 00 01 00 04 00 00 00 ................
0020 00 00 78 00 00 00 00 00 00 00 00 00 00 00 00 00 ..x.............
0030 00 00 00 00 00 00 00 00 00 00 00 00 80 00 00 80 ................
0040 00 00 00 80 80 00 80 00 00 00 80 00 80 00 80 80 ................
0050 00 00 80 80 80 00 c0 c0 c0 00 00 00 ff 00 00 ff ................
0060 00 00 00 ff ff 00 ff 00 00 00 ff 00 ff 00 ff ff ................
0070 00 00 ff ff ff 00 88 88 88 88 88 88 88 88 88 88 ................
0080 80 88 88 88 88 88 88 88 80 08 88 88 88 88 88 88 ................
0090 80 00 88 88 88 88 88 88 80 00 08 88 88 88 88 88 ................
00a0 80 00 00 88 88 88 88 88 80 00 00 08 88 88 88 88 ................
00b0 80 00 00 00 88 88 88 88 80 00 00 08 88 88 88 88 ................
00c0 80 00 00 88 88 88 88 88 80 00 08 88 88 88 88 88 ................
00d0 80 00 88 88 88 88 88 88 80 08 88 88 88 88 88 88 ................
00e0 80 88 88 88 88 88 88 88 88 88 88 88 88 88 ..............
Since the release 10, PB is unicode (utf-16le)-aware. So the legacy Len() is implicit LenW() (as other string functions, and dealing with legacy data could imply to use explicit LenA()).
Are you sure that you are getting some utf-16le encoding ? Given the following function, what does it return on a string containing your data, if you call it with hexdump_blob(blob(your_string))?
Paste this code into the source code of a new global function named hexdump_blob to have an hexadecimal display (hex editor like) for blob contents.
global type hexdump_blob from function_object
end type
forward prototypes
global function string hexdump_blob (blob abl_data, boolean ab_fill_lastline)
end prototypes
global function string hexdump_blob (blob abl_data, boolean ab_fill_lastline);//hexify a blob content
string ls_tohex = "0123456789ABCDEF"
string ls_msg = "", ls_line, ls_binary
long i, j, length
byte b
string ls_fill
if isnull( abl_data ) then return ""
if ab_fill_lastline then
ls_fill = " __"
else
ls_fill = " "
end if
length = len( abl_data )
for i = 1 to length
GetByte( abl_data, i, b )
ls_line += mid( ls_tohex, 1+ mod(int(b/16),16), 1)
ls_line += mid( ls_tohex, 1+ mod(b,16), 1)
ls_line += " "
ls_binary += string( iif(b>31 and b<128,char(b)," "))
if mod(i,16) = 0 and i > 0 then
ls_binary = replaceall( ls_binary, "~r", "·") //no cr/lf
ls_binary = replaceall( ls_binary, "~n", "·")
ls_binary = replaceall( ls_binary, "~t", "·")
ls_msg += "[" + string( i - 16, "0000") + "] " + ls_line + "~t" + ls_binary + "~r~n"
ls_line = ""
ls_binary = ""
end if
next
i -- // i - 1 due to the last loop in for
ls_line += fill(ls_fill, 3 * ( 16 - mod(i, 16) ) )
ls_msg += "[" + string( i - mod(i,16), "0000") + "] " + ls_line + "~t" + ls_binary
return ls_msg
end function
Also, here is the replaceall() function that is used by hexdump_blob()
global type replaceall from function_object
end type
forward prototypes
global function string replaceall (string as_source, string as_pattern, string as_replace)
end prototypes
global function string replaceall (string as_source, string as_pattern, string as_replace);//remplace toute les occurences de as_pattern de as_source par as_replace
string ls_target
long i, j
ls_target=""
i = 1
j = 1
do
i = pos( as_source, as_pattern, j )
if i>0 then
ls_target += mid( as_source, j, i - j )
ls_target += as_replace
j = i + len( as_pattern )
else
ls_target += mid( as_source, j )
end if
loop while i>0
return ls_target
end function
and the iif() that simulates the C ternary operator, or the visual basic iif()
global type iif from function_object
end type
forward prototypes
global function any iif (boolean ab_cond, any aa_true, any aa_false)
end prototypes
global function any iif (boolean ab_cond, any aa_true, any aa_false);
// simulates the VB iif or C ternary operator
if ab_cond then
return aa_true
else
return aa_false
end if
end function
Wouldn't you want to use the LenA() method?
http://www.techno-kitten.com/Changes_to_PowerBuilder/New_in_PowerBuilder_10/PB10New_-_Unicode_Support/PB10New_-_Unicode_Related_Chan/PB10New_-_String-Related_Funct/pb10new_-_modified_processing_.html