Search Results

Search found 6123 results on 245 pages for 'unsigned char'.

Page 41/245 | < Previous Page | 37 38 39 40 41 42 43 44 45 46 47 48  | Next Page >

  • C Array of string

    - by Meko
    HI. This is maybe simple question but I want to create two dimensional array and add it string like in java string str = "text" ; string [][] array = new [][] string ; array[i][j] = str ; But in C there is no string .I tried like this but here strcpy() gives error.It returns to assembly code. I am trying to read line by line from text and split line by space and add them to structure.But first I think that I must add each line and row in array and then making iteration and adding to structures fields. static const char filename[] = "student.txt"; FILE *file = fopen ( filename, "r" ); char line [ 128 ]; /* or other suitable maximum line size */ char delims [ ]=" "; char *result =NULL; char list[15]; char arra[128][128]; int i=0; int j=0; struct { char gruppa[10]; char familiya[20]; int uchaste; struct { int firsth; int second; int third; int fourht; int fifth; } exam; }student; for(i=0; i<128; i++) for(j=0; j<128; j++) arra[i][j] = '\0'; for(i=0; i<15; i++) list[i] = '\0'; if ( file != NULL ) { while ( fgets ( line, sizeof line, file ) != NULL ) { result = strtok(line,delims); while (result !=NULL) { strcpy(list,("%s",result)); strcpy(arra[i][j],list); // Here it gives errror j++; result = strtok(NULL,delims); } j=0; i++; } fclose ( file ); } else { perror ( filename ); } getchar(); return 0; }

    Read the article

  • replacing a path with sed

    - by compie
    How can I use sed to replace this line char * path_list_[1] = { "/some/random/path" }; with this line char * path_list_[2] = { "lib/foo", "lib/bar" }; in a file named source.c Notes: * The path is really random. * Your solution should only change this line in source.c * I'm only interested in a sed oneliner. You can use this Python regex as a starting point: text = re.sub('static const char \* path_list_\[1\] = \{ "[^"]*" \};', 'static const char * path_list_[2] = { "lib/sun", "lib/matlab" };', text)

    Read the article

  • How to fix a warning message associated with strlen() used in Yacc?

    - by user547894
    Hello! Please i need your help. Basically, I am facing this warning message upon compiling with gcc, and am not able to deduce the error: Here are the details: The warning message i am receiving is literrally as follows: y.tab.c: In function ‘yyparse’: y.tab.c:1317 warning: incompatible implicit declaration of built-in function ‘strlen’ My Lex File looks like: %{ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include "y.tab.h" void yyerror(const char*); char *ptrStr; %} %START nameState %% "Name:" { BEGIN nameState; } <nameState>.+ { ptrStr = (char *)calloc(strlen(yytext)+1, sizeof(char)); strcpy(ptrStr, yytext); yylval.sValue = ptrStr; return sText; } %% int main(int argc, char *argv[]) { if ( argc < 3 ) { printf("Two args are needed: input and output"); } else { yyin = fopen(argv[1], "r"); yyout = fopen(argv[2], "w"); yyparse(); fclose(yyin); fclose(yyout); } return 0; } My Yacc file is as follows: %{ #include <stdio.h> #include <stdlib.h> #include <ctype.h> #include "y.tab.h" void yyerror(const char*); int yywrap(); extern FILE *yyout; %} %union { int iValue; char* sValue; }; %token <sValue> sText %token nameToken %% StartName: /* for empty */ | sName ; sName: sText { fprintf(yyout, "The Name is: %s", $1); fprintf(yyout, "The Length of the Name is: %d", strlen($1)); } ; %% void yyerror(const char *str) { fprintf(stderr,"error: %s\n",str); } int yywrap() { return 1; } *I was wondering how to remove this warning message. Please any suggestions are highly appreciated! Thanks in advance.

    Read the article

  • Xerces conflicts string.h

    - by Velthune
    Compiling my program I have this error: /usr/include/xercesc/util/Compilers/GCCDefs.hpp:133:60: error: declaration of ‘int strcasecmp(const char*, const char*)’ has a different exception specifier /usr/include/string.h:536:12: error: from previous declaration ‘int strcasecmp(const char*, const char*) throw ()’ make: *** [src/test/VFTImageMaterial.o] Error 1 Any idea about this conflict with string.h?

    Read the article

  • Split a binary file into chunks c++

    - by L4nce0
    I've been bashing my head against trying to first divide up a file into chunks, for the purpose of sending over sockets. I can read / write a file easily without splitting it into chunks. The code below runs, works, kinda. It will write a textfile and has a garbage character. Which if this was just for txt, no problem. Jpegs aren't working with said garbage. Been at it for a few days, so I've done my research, and it's time to get some help. I do want to stick strictly to binary readers, as this need to handle any file. I've seen a lot of slick examples out there. (none of them worked for me with jpgs) Mostly something along the lines of while(file)... I subscribe to the, if you know the size, use a for-loop, not a while-loop camp. Thank you for the help!! vector<char*> readFile(const char* fn){ vector<char*> v; ifstream::pos_type size; char * memblock; ifstream file; file.open(fn,ios::in|ios::binary|ios::ate); if (file.is_open()) { size = fileS(fn); file.seekg (0, ios::beg); int bs = size/3; // arbitrary. Actual program will use the socket send size int ws = 0; int i = 0; for(i = 0; i < size; i+=bs){ if(i+bs > size) ws = size%bs; else ws = bs; memblock = new char [ws]; file.read (memblock, ws); v.push_back(memblock); } } else{ exit(-4); } return v; } int main(int argc, char **argv) { vector<char*> v = readFile("foo.txt"); ofstream myFile ("bar.txt", ios::out | ios::binary); for(vector<char*>::iterator it = v.begin(); it!=v.end(); ++it ){ myFile.write(*it,strlen(*it)); } }

    Read the article

  • Bitlocker-to-go on fixed drive

    - by Unsigned
    Scenario Two drives are connected to a computer. One via a SATA-to-USB interface, the other directly via a SATA-to-eSATA cable. The drive on USB appears as a removable drive, the drive on eSATA appears as a fixed drive. Both use NTFS. The USB drive offers Bitlocker-To-Go, the eSATA drive only offers BitLocker. Question It is my understanding that drives encrypted with BitLocker-To-Go include an app to allow Windows XP read-only access to the volume. Is this the only difference, and is there a way to use Bitlocker-To-Go on the eSATA drive? Update Another difference is found here: The recovery key is required when a BitLocker-protected fixed data drive configured for automatic unlocking is moved to another computer.[1] Assuming that does not apply to removable drives.

    Read the article

  • Remote Desktop doesn't recognize username change

    - by Unsigned
    There are two active user accounts on the Windows 7 Professional server, Owner, and Guest. Owner is an Administrator with a password. Guest is the default Guest account with no password, but has been added to Remote Desktop Users. When attempting to connect to the server via a Windows 7 Professional client, Guest accepts RD connections fine, however, Owner throws an error "Unable to connect to Local Security Authority." I created a new Administrator account, named Remote, with the same password as Owner. Remote Desktop worked perfectly. I then deleted Owner, and renamed Remote to Owner. Now, Remote Desktop gives the same error ("Unable to connect to Local Security Authority") when attempting to log into the new Owner. However, attempting to log into Remote (even though it was renamed to Owner), works. Completely at a loss here, what is going on? Why won't Owner work, and why does Remote Desktop still use the old name on the renamed account?

    Read the article

  • Does BitLocker reduce write reliability?

    - by Unsigned
    For the purposes of this question, BitLocker refers to the BitLocker-to-go variety on a disk with write-caching disabled. NTFS supports metadata journaling, which, although not completely failsafe, does mitigate certain types of potential filesystem errors. Assuming an NTFS volume is protected with BitLocker, does this reduce the failure tolerance? Would a power failure during a write to an NTFS volume, that's protected with BitLocker, be more prone to corruption than on an unencrypted NTFS volume?

    Read the article

  • Dissect System Restore snapshots

    - by Unsigned
    Is there any way to map the A000????.??? filenames in the System Volume Information to their original names, without restoring them? The reason I ask is that several files in one user's System Volume Information RP1 were infected by a rootkit. Although they've been removed, I'd like to be able to figure out what they were originally. A0001253.sys and A0001211.sys are not very helpful names. :) It happened on two systems, one XP SP2, the other XP SP3.

    Read the article

  • Scenario - NTFS Symbolic Link or Junction?

    - by Unsigned
    Differences Absolute Relative File Directory UNC Symbolic link ? ? ? ? ? Junction ? x x ? x Scenario Let's assume we're creating a reparse point to create the redirect C:\SomeDir => D:\SomeDir Since this scenario only requires local, absolute paths, either a junction or symlink would work. In this situation, is there any advantage to using one or the other? Assume Windows 7 for the OS, disregarding backward-compatibility (prior to Vista, symlinks are not supported). Update I have found another difference. Symbolic Link - Link's permissions only affect delete/rename operations on the link itself, read/write access (to the target) is governed by the target's permissions Junction - Junction's permissions affect enumeration, revoking permissions on the junction will deny file listing through that junction, even if the target folder has more permissive ACLs The permissions make it interesting, as symlinks can allow legacy applications to access configuration files in UAC-restricted areas (such as %ProgramFiles%) without changing existing access permissions, by storing the files in a non-restricted location and creating symlinks in the restricted directory.

    Read the article

  • Thunderbird message sorting - wrong dates

    - by Unsigned
    Thunderbird 3 is having a problem with one of my IMAP accounts. When sorted by date, it displays 10-15 messages at the top (newest) when in fact they are very old message. (pre-2010, over a year old, some up to 6-7 years old) It's not game-breaking, but it is annoying, as I have to look past those to check for "new" messages. Is there any way to fix this? I'd considered re-downloading all the messages via IMAP, but that would take weeks (50,000 messages). When I open it, it displays the correct date, also when I use "View Source" the Date: header has the correct date (2009, 2006, etc). Is there any way to make Thunderbird realize that it should be sorted down with the rest of the 2006/2009 messages? None of my other IMAP accounts (many with the same host server) have this issue.

    Read the article

  • Prevent applications from being run as administrator

    - by Unsigned
    Background Most installation toolkits have the ability to launch, automatically or otherwise, external programs after installation. This is often appears in the installer via such options as "Show readme", or "Start program". Issue The problem is, many of these installers are poorly coded, and do not drop permissions appropriately, for example, opening the application's homepage in the browser... launching the browser with the installer's Administrative privileges, or a "High" UAC integrity level. This has the potential to open up security breaches, by opening up a webpage (and possibly browser addons), that are now running with elevated permissions. Question The question is: Is there a way to prevent certain applications (such as a web browser) from ever being launched with Administrative privileges, i.e., an automatic drop-privilege?

    Read the article

  • Prevent specific applications from being run as administrator

    - by Unsigned
    Background Most installation toolkits have the ability to launch, automatically or otherwise, external programs after installation. This is often appears in the installer via such options as "Show readme", or "Start program". Issue The problem is, many of these installers are poorly coded, and do not drop permissions appropriately. For example, starting the application automatically, or opening the application's homepage in the browser, often results in launching the application or browser with the installer's Administrative privileges, or a "High" UAC integrity level! This has the potential to open up security breaches, by opening up the installed application, or a web page (and possibly browser add-ons), that are now running with elevated permissions. (This is the reason I strongly recommend never choosing auto-launch options when installing software.) Question The question is: Is there a way to prevent certain applications (such as a web browser) from ever being launched with Administrative privileges, i.e., an automatic drop-privilege?

    Read the article

  • Large recovery partitions

    - by Unsigned
    Is there any good reason as to why factory restore partitions are generally much larger than they need to be? Examples I have found in my own experience: Dell XPS laptop Partition: 13.67 GB Used: 6.68 GB Dell Inspiron laptop Partition: 14.7 GB Used: 7.2 GB Toshiba laptop Partition: 15.3 GB Used: 9 GB In all cases, shrinking the partition to only slightly more than the Used space had no ill effects on future factory restorations. Why the exorbitant amount of extra space, given that neither of the three computers ever writes any data to the recovery partition? Is there a good reason I'm overlooking?

    Read the article

  • SQL Server &ndash; Undelete a Table and Restore a Single Table from Backup

    - by Mladen Prajdic
    This post is part of the monthly community event called T-SQL Tuesday started by Adam Machanic (blog|twitter) and hosted by someone else each month. This month the host is Sankar Reddy (blog|twitter) and the topic is Misconceptions in SQL Server. You can follow posts for this theme on Twitter by looking at #TSQL2sDay hashtag. Let me start by saying: This code is a crazy hack that is to never be used unless you really, really have to. Really! And I don’t think there’s a time when you would really have to use it for real. Because it’s a hack there are number of things that can go wrong so play with it knowing that. I’ve managed to totally corrupt one database. :) Oh… and for those saying: yeah yeah.. you have a single table in a file group and you’re restoring that, I say “nay nay” to you. As we all know SQL Server can’t do single table restores from backup. This is kind of a obvious thing due to different relational integrity (RI) concerns. Since we have to maintain that we have to restore all tables represented in a RI graph. For this exercise i say BAH! to those concerns. Note that this method “works” only for simple tables that don’t have LOB and off rows data. The code can be expanded to include those but I’ve tried to leave things “simple”. Note that for this to work our table needs to be relatively static data-wise. This doesn’t work for OLTP table. Products are a perfect example of static data. They don’t change much between backups, pretty much everything depends on them and their table is one of those tables that are relatively easy to accidentally delete everything from. This only works if the database is in Full or Bulk-Logged recovery mode for tables where the contents have been deleted or truncated but NOT when a table was dropped. Everything we’ll talk about has to be done before the data pages are reused for other purposes. After deletion or truncation the pages are marked as reusable so you have to act fast. The best thing probably is to put the database into single user mode ASAP while you’re performing this procedure and return it to multi user after you’re done. How do we do it? We will be using an undocumented but known DBCC commands: DBCC PAGE, an undocumented function sys.fn_dblog and a little known DATABASE RESTORE PAGE option. All tests will be on a copy of Production.Product table in AdventureWorks database called Production.Product1 because the original table has FK constraints that prevent us from truncating it for testing. -- create a duplicate table. This doesn't preserve indexes!SELECT *INTO AdventureWorks.Production.Product1FROM AdventureWorks.Production.Product   After we run this code take a full back to perform further testing.   First let’s see what the difference between DELETE and TRUNCATE is when it comes to logging. With DELETE every row deletion is logged in the transaction log. With TRUNCATE only whole data page deallocations are logged in the transaction log. Getting deleted data pages is simple. All we have to look for is row delete entry in the sys.fn_dblog output. But getting data pages that were truncated from the transaction log presents a bit of an interesting problem. I will not go into depths of IAM(Index Allocation Map) and PFS (Page Free Space) pages but suffice to say that every IAM page has intervals that tell us which data pages are allocated for a table and which aren’t. If we deep dive into the sys.fn_dblog output we can see that once you truncate a table all the pages in all the intervals are deallocated and this is shown in the PFS page transaction log entry as deallocation of pages. For every 8 pages in the same extent there is one PFS page row in the transaction log. This row holds information about all 8 pages in CSV format which means we can get to this data with some parsing. A great help for parsing this stuff is Peter Debetta’s handy function dbo.HexStrToVarBin that converts hexadecimal string into a varbinary value that can be easily converted to integer tus giving us a readable page number. The shortened (columns removed) sys.fn_dblog output for a PFS page with CSV data for 1 extent (8 data pages) looks like this: -- [Page ID] is displayed in hex format. -- To convert it to readable int we'll use dbo.HexStrToVarBin function found at -- http://sqlblog.com/blogs/peter_debetta/archive/2007/03/09/t-sql-convert-hex-string-to-varbinary.aspx -- This function must be installed in the master databaseSELECT Context, AllocUnitName, [Page ID], DescriptionFROM sys.fn_dblog(NULL, NULL)WHERE [Current LSN] = '00000031:00000a46:007d' The pages at the end marked with 0x00—> are pages that are allocated in the extent but are not part of a table. We can inspect the raw content of each data page with a DBCC PAGE command: -- we need this trace flag to redirect output to the query window.DBCC TRACEON (3604); -- WITH TABLERESULTS gives us data in table format instead of message format-- we use format option 3 because it's the easiest to read and manipulate further onDBCC PAGE (AdventureWorks, 1, 613, 3) WITH TABLERESULTS   Since the DBACC PAGE output can be quite extensive I won’t put it here. You can see an example of it in the link at the beginning of this section. Getting deleted data back When we run a delete statement every row to be deleted is marked as a ghost record. A background process periodically cleans up those rows. A huge misconception is that the data is actually removed. It’s not. Only the pointers to the rows are removed while the data itself is still on the data page. We just can’t access it with normal means. To get those pointers back we need to restore every deleted page using the RESTORE PAGE option mentioned above. This restore must be done from a full backup, followed by any differential and log backups that you may have. This is necessary to bring the pages up to the same point in time as the rest of the data.  However the restore doesn’t magically connect the restored page back to the original table. It simply replaces the current page with the one from the backup. After the restore we use the DBCC PAGE to read data directly from all data pages and insert that data into a temporary table. To finish the RESTORE PAGE  procedure we finally have to take a tail log backup (simple backup of the transaction log) and restore it back. We can now insert data from the temporary table to our original table by hand. Getting truncated data back When we run a truncate the truncated data pages aren’t touched at all. Even the pointers to rows stay unchanged. Because of this getting data back from truncated table is simple. we just have to find out which pages belonged to our table and use DBCC PAGE to read data off of them. No restore is necessary. Turns out that the problems we had with finding the data pages is alleviated by not having to do a RESTORE PAGE procedure. Stop stalling… show me The Code! This is the code for getting back deleted and truncated data back. It’s commented in all the right places so don’t be afraid to take a closer look. Make sure you have a full backup before trying this out. Also I suggest that the last step of backing and restoring the tail log is performed by hand. USE masterGOIF OBJECT_ID('dbo.HexStrToVarBin') IS NULL RAISERROR ('No dbo.HexStrToVarBin installed. Go to http://sqlblog.com/blogs/peter_debetta/archive/2007/03/09/t-sql-convert-hex-string-to-varbinary.aspx and install it in master database' , 18, 1) SET NOCOUNT ONBEGIN TRY DECLARE @dbName VARCHAR(1000), @schemaName VARCHAR(1000), @tableName VARCHAR(1000), @fullBackupName VARCHAR(1000), @undeletedTableName VARCHAR(1000), @sql VARCHAR(MAX), @tableWasTruncated bit; /* THE FIRST LINE ARE OUR INPUT PARAMETERS In this case we're trying to recover Production.Product1 table in AdventureWorks database. My full backup of AdventureWorks database is at e:\AW.bak */ SELECT @dbName = 'AdventureWorks', @schemaName = 'Production', @tableName = 'Product1', @fullBackupName = 'e:\AW.bak', @undeletedTableName = '##' + @tableName + '_Undeleted', @tableWasTruncated = 0, -- copy the structure from original table to a temp table that we'll fill with restored data @sql = 'IF OBJECT_ID(''tempdb..' + @undeletedTableName + ''') IS NOT NULL DROP TABLE ' + @undeletedTableName + ' SELECT *' + ' INTO ' + @undeletedTableName + ' FROM [' + @dbName + '].[' + @schemaName + '].[' + @tableName + ']' + ' WHERE 1 = 0' EXEC (@sql) IF OBJECT_ID('tempdb..#PagesToRestore') IS NOT NULL DROP TABLE #PagesToRestore /* FIND DATA PAGES WE NEED TO RESTORE*/ CREATE TABLE #PagesToRestore ([ID] INT IDENTITY(1,1), [FileID] INT, [PageID] INT, [SQLtoExec] VARCHAR(1000)) -- DBCC PACE statement to run later RAISERROR ('Looking for deleted pages...', 10, 1) -- use T-LOG direct read to get deleted data pages INSERT INTO #PagesToRestore([FileID], [PageID], [SQLtoExec]) EXEC('USE [' + @dbName + '];SELECT FileID, PageID, ''DBCC TRACEON (3604); DBCC PAGE ([' + @dbName + '], '' + FileID + '', '' + PageID + '', 3) WITH TABLERESULTS'' as SQLToExecFROM (SELECT DISTINCT LEFT([Page ID], 4) AS FileID, CONVERT(VARCHAR(100), ' + 'CONVERT(INT, master.dbo.HexStrToVarBin(SUBSTRING([Page ID], 6, 20)))) AS PageIDFROM sys.fn_dblog(NULL, NULL)WHERE AllocUnitName LIKE ''%' + @schemaName + '.' + @tableName + '%'' ' + 'AND Context IN (''LCX_MARK_AS_GHOST'', ''LCX_HEAP'') AND Operation in (''LOP_DELETE_ROWS''))t');SELECT *FROM #PagesToRestore -- if upper EXEC returns 0 rows it means the table was truncated so find truncated pages IF (SELECT COUNT(*) FROM #PagesToRestore) = 0 BEGIN RAISERROR ('No deleted pages found. Looking for truncated pages...', 10, 1) -- use T-LOG read to get truncated data pages INSERT INTO #PagesToRestore([FileID], [PageID], [SQLtoExec]) -- dark magic happens here -- because truncation simply deallocates pages we have to find out which pages were deallocated. -- we can find this out by looking at the PFS page row's Description column. -- for every deallocated extent the Description has a CSV of 8 pages in that extent. -- then it's just a matter of parsing it. -- we also remove the pages in the extent that weren't allocated to the table itself -- marked with '0x00-->00' EXEC ('USE [' + @dbName + '];DECLARE @truncatedPages TABLE(DeallocatedPages VARCHAR(8000), IsMultipleDeallocs BIT);INSERT INTO @truncatedPagesSELECT REPLACE(REPLACE(Description, ''Deallocated '', ''Y''), ''0x00-->00 '', ''N'') + '';'' AS DeallocatedPages, CHARINDEX('';'', Description) AS IsMultipleDeallocsFROM (SELECT DISTINCT LEFT([Page ID], 4) AS FileID, CONVERT(VARCHAR(100), CONVERT(INT, master.dbo.HexStrToVarBin(SUBSTRING([Page ID], 6, 20)))) AS PageID, DescriptionFROM sys.fn_dblog(NULL, NULL)WHERE Context IN (''LCX_PFS'') AND Description LIKE ''Deallocated%'' AND AllocUnitName LIKE ''%' + @schemaName + '.' + @tableName + '%'') t;SELECT FileID, PageID , ''DBCC TRACEON (3604); DBCC PAGE ([' + @dbName + '], '' + FileID + '', '' + PageID + '', 3) WITH TABLERESULTS'' as SQLToExecFROM (SELECT LEFT(PageAndFile, 1) as WasPageAllocatedToTable , SUBSTRING(PageAndFile, 2, CHARINDEX('':'', PageAndFile) - 2 ) as FileID , CONVERT(VARCHAR(100), CONVERT(INT, master.dbo.HexStrToVarBin(SUBSTRING(PageAndFile, CHARINDEX('':'', PageAndFile) + 1, LEN(PageAndFile))))) as PageIDFROM ( SELECT SUBSTRING(DeallocatedPages, delimPosStart, delimPosEnd - delimPosStart) as PageAndFile, IsMultipleDeallocs FROM ( SELECT *, CHARINDEX('';'', DeallocatedPages)*(N-1) + 1 AS delimPosStart, CHARINDEX('';'', DeallocatedPages)*N AS delimPosEnd FROM @truncatedPages t1 CROSS APPLY (SELECT TOP (case when t1.IsMultipleDeallocs = 1 then 8 else 1 end) ROW_NUMBER() OVER(ORDER BY number) as N FROM master..spt_values) t2 )t)t)tWHERE WasPageAllocatedToTable = ''Y''') SELECT @tableWasTruncated = 1 END DECLARE @lastID INT, @pagesCount INT SELECT @lastID = 1, @pagesCount = COUNT(*) FROM #PagesToRestore SELECT @sql = 'Number of pages to restore: ' + CONVERT(VARCHAR(10), @pagesCount) IF @pagesCount = 0 RAISERROR ('No data pages to restore.', 18, 1) ELSE RAISERROR (@sql, 10, 1) -- If the table was truncated we'll read the data directly from data pages without restoring from backup IF @tableWasTruncated = 0 BEGIN -- RESTORE DATA PAGES FROM FULL BACKUP IN BATCHES OF 200 WHILE @lastID <= @pagesCount BEGIN -- create CSV string of pages to restore SELECT @sql = STUFF((SELECT ',' + CONVERT(VARCHAR(100), FileID) + ':' + CONVERT(VARCHAR(100), PageID) FROM #PagesToRestore WHERE ID BETWEEN @lastID AND @lastID + 200 ORDER BY ID FOR XML PATH('')), 1, 1, '') SELECT @sql = 'RESTORE DATABASE [' + @dbName + '] PAGE = ''' + @sql + ''' FROM DISK = ''' + @fullBackupName + '''' RAISERROR ('Starting RESTORE command:' , 10, 1) WITH NOWAIT; RAISERROR (@sql , 10, 1) WITH NOWAIT; EXEC(@sql); RAISERROR ('Restore DONE' , 10, 1) WITH NOWAIT; SELECT @lastID = @lastID + 200 END /* If you have any differential or transaction log backups you should restore them here to bring the previously restored data pages up to date */ END DECLARE @dbccSinglePage TABLE ( [ParentObject] NVARCHAR(500), [Object] NVARCHAR(500), [Field] NVARCHAR(500), [VALUE] NVARCHAR(MAX) ) DECLARE @cols NVARCHAR(MAX), @paramDefinition NVARCHAR(500), @SQLtoExec VARCHAR(1000), @FileID VARCHAR(100), @PageID VARCHAR(100), @i INT = 1 -- Get deleted table columns from information_schema view -- Need sp_executeSQL because database name can't be passed in as variable SELECT @cols = 'select @cols = STUFF((SELECT '', ['' + COLUMN_NAME + '']''FROM ' + @dbName + '.INFORMATION_SCHEMA.COLUMNSWHERE TABLE_NAME = ''' + @tableName + ''' AND TABLE_SCHEMA = ''' + @schemaName + '''ORDER BY ORDINAL_POSITIONFOR XML PATH('''')), 1, 2, '''')', @paramDefinition = N'@cols nvarchar(max) OUTPUT' EXECUTE sp_executesql @cols, @paramDefinition, @cols = @cols OUTPUT -- Loop through all the restored data pages, -- read data from them and insert them into temp table -- which you can then insert into the orignial deleted table DECLARE dbccPageCursor CURSOR GLOBAL FORWARD_ONLY FOR SELECT [FileID], [PageID], [SQLtoExec] FROM #PagesToRestore ORDER BY [FileID], [PageID] OPEN dbccPageCursor; FETCH NEXT FROM dbccPageCursor INTO @FileID, @PageID, @SQLtoExec; WHILE @@FETCH_STATUS = 0 BEGIN RAISERROR ('---------------------------------------------', 10, 1) WITH NOWAIT; SELECT @sql = 'Loop iteration: ' + CONVERT(VARCHAR(10), @i); RAISERROR (@sql, 10, 1) WITH NOWAIT; SELECT @sql = 'Running: ' + @SQLtoExec RAISERROR (@sql, 10, 1) WITH NOWAIT; -- if something goes wrong with DBCC execution or data gathering, skip it but print error BEGIN TRY INSERT INTO @dbccSinglePage EXEC (@SQLtoExec) -- make the data insert magic happen here IF (SELECT CONVERT(BIGINT, [VALUE]) FROM @dbccSinglePage WHERE [Field] LIKE '%Metadata: ObjectId%') = OBJECT_ID('['+@dbName+'].['+@schemaName +'].['+@tableName+']') BEGIN DELETE @dbccSinglePage WHERE NOT ([ParentObject] LIKE 'Slot % Offset %' AND [Object] LIKE 'Slot % Column %') SELECT @sql = 'USE tempdb; ' + 'IF (OBJECTPROPERTY(object_id(''' + @undeletedTableName + '''), ''TableHasIdentity'') = 1) ' + 'SET IDENTITY_INSERT ' + @undeletedTableName + ' ON; ' + 'INSERT INTO ' + @undeletedTableName + '(' + @cols + ') ' + STUFF((SELECT ' UNION ALL SELECT ' + STUFF((SELECT ', ' + CASE WHEN VALUE = '[NULL]' THEN 'NULL' ELSE '''' + [VALUE] + '''' END FROM ( -- the unicorn help here to correctly set ordinal numbers of columns in a data page -- it's turning STRING order into INT order (1,10,11,2,21 into 1,2,..10,11...21) SELECT [ParentObject], [Object], Field, VALUE, RIGHT('00000' + O1, 6) AS ParentObjectOrder, RIGHT('00000' + REVERSE(LEFT(O2, CHARINDEX(' ', O2)-1)), 6) AS ObjectOrder FROM ( SELECT [ParentObject], [Object], Field, VALUE, REPLACE(LEFT([ParentObject], CHARINDEX('Offset', [ParentObject])-1), 'Slot ', '') AS O1, REVERSE(LEFT([Object], CHARINDEX('Offset ', [Object])-2)) AS O2 FROM @dbccSinglePage WHERE t.ParentObject = ParentObject )t)t ORDER BY ParentObjectOrder, ObjectOrder FOR XML PATH('')), 1, 2, '') FROM @dbccSinglePage t GROUP BY ParentObject FOR XML PATH('') ), 1, 11, '') + ';' RAISERROR (@sql, 10, 1) WITH NOWAIT; EXEC (@sql) END END TRY BEGIN CATCH SELECT @sql = 'ERROR!!!' + CHAR(10) + CHAR(13) + 'ErrorNumber: ' + ERROR_NUMBER() + '; ErrorMessage' + ERROR_MESSAGE() + CHAR(10) + CHAR(13) + 'FileID: ' + @FileID + '; PageID: ' + @PageID RAISERROR (@sql, 10, 1) WITH NOWAIT; END CATCH DELETE @dbccSinglePage SELECT @sql = 'Pages left to process: ' + CONVERT(VARCHAR(10), @pagesCount - @i) + CHAR(10) + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10) + CHAR(13), @i = @i+1 RAISERROR (@sql, 10, 1) WITH NOWAIT; FETCH NEXT FROM dbccPageCursor INTO @FileID, @PageID, @SQLtoExec; END CLOSE dbccPageCursor; DEALLOCATE dbccPageCursor; EXEC ('SELECT ''' + @undeletedTableName + ''' as TableName; SELECT * FROM ' + @undeletedTableName)END TRYBEGIN CATCH SELECT ERROR_NUMBER() AS ErrorNumber, ERROR_MESSAGE() AS ErrorMessage IF CURSOR_STATUS ('global', 'dbccPageCursor') >= 0 BEGIN CLOSE dbccPageCursor; DEALLOCATE dbccPageCursor; ENDEND CATCH-- if the table was deleted we need to finish the restore page sequenceIF @tableWasTruncated = 0BEGIN -- take a log tail backup and then restore it to complete page restore process DECLARE @currentDate VARCHAR(30) SELECT @currentDate = CONVERT(VARCHAR(30), GETDATE(), 112) RAISERROR ('Starting Log Tail backup to c:\Temp ...', 10, 1) WITH NOWAIT; PRINT ('BACKUP LOG [' + @dbName + '] TO DISK = ''c:\Temp\' + @dbName + '_TailLogBackup_' + @currentDate + '.trn''') EXEC ('BACKUP LOG [' + @dbName + '] TO DISK = ''c:\Temp\' + @dbName + '_TailLogBackup_' + @currentDate + '.trn''') RAISERROR ('Log Tail backup done.', 10, 1) WITH NOWAIT; RAISERROR ('Starting Log Tail restore from c:\Temp ...', 10, 1) WITH NOWAIT; PRINT ('RESTORE LOG [' + @dbName + '] FROM DISK = ''c:\Temp\' + @dbName + '_TailLogBackup_' + @currentDate + '.trn''') EXEC ('RESTORE LOG [' + @dbName + '] FROM DISK = ''c:\Temp\' + @dbName + '_TailLogBackup_' + @currentDate + '.trn''') RAISERROR ('Log Tail restore done.', 10, 1) WITH NOWAIT;END-- The last step is manual. Insert data from our temporary table to the original deleted table The misconception here is that you can do a single table restore properly in SQL Server. You can't. But with little experimentation you can get pretty close to it. One way to possible remove a dependency on a backup to retrieve deleted pages is to quickly run a similar script to the upper one that gets data directly from data pages while the rows are still marked as ghost records. It could be done if we could beat the ghost record cleanup task.

    Read the article

  • qT quncompress gzip data

    - by talei
    Hello, I stumble upon a problem, and can't find a solution. So what I want to do is uncompress data in qt, using qUncompress(QByteArray), send from www in gzip format. I used wireshark to determine that this is valid gzip stream, also tested with zip/rar and both can uncompress it. Code so far, is like this: static const char dat[40] = { 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x03, 0xaa, 0x2e, 0x2e, 0x49, 0x2c, 0x29, 0x2d, 0xb6, 0x4a, 0x4b, 0xcc, 0x29, 0x4e, 0xad, 0x05, 0x00, 0x00, 0x00, 0xff, 0xff, 0x03, 0x00, 0x2a, 0x63, 0x18, 0xc5, 0x0e, 0x00, 0x00, 0x00 }; //this data contains string: {status:false}, in gzip format QByteArray data; data.append( dat, sizeof(dat) ); unsigned int size = 14; //expected uncompresed size, reconstruct it BigEndianes //prepand expected uncompressed size, last 4 byte in dat 0x0e = 14 QByteArray dataPlusSize; dataPlusSize.append( (unsigned int)((size >> 24) & 0xFF)); dataPlusSize.append( (unsigned int)((size >> 16) & 0xFF)); dataPlusSize.append( (unsigned int)((size >> 8) & 0xFF)); dataPlusSize.append( (unsigned int)((size >> 0) & 0xFF)); QByteArray uncomp = qUncompress( dataPlusSize ); qDebug() << uncomp; And uncompression fails with: qUncompress: Z_DATA_ERROR: Input data is corrupted. AFAIK gzip consist of 10 byte header, DEFLATE peyload, 12 byte trailer ( 8 byte CRC32 + 4 byte ISIZE - uncompresed data size ). Striping header and trailer should leave me with DEFLATE data stream, qUncompress yields same error. I checked with data string compressed in PHP, like this: $stringData = gzcompress( "{status:false}", 1); and qUncompress uncompress that data.(I didn't see and gzip header though i.e. ID1 = 0x1f, ID2 = 0x8b ) I checked above code with debug, and error occurs at: if ( #endif ((BITS(8) << 8) + (hold >> 8)) % 31) { //here is error, WHY? long unsigned int hold = 35615 strm->msg = (char *)"incorrect header check"; state->mode = BAD; break; } inflate.c line 610. I know that qUncompress is simply a wrapper to zlib, so I suppose it should handle gzip without any problem. Any comments are more then welcome. Best regards

    Read the article

  • C++ _beginthreadex in cygwin

    - by Hugh
    Hello all, I am aware that _beginthreadex is part of the MSCVRT functions and therefore not accessible via Cygwin/MinGW uintptr_t _beginthreadex( void *security, unsigned stack_size, unsigned ( __stdcall *start_address )( void * ), void *arglist, unsigned initflag, unsigned *thrdaddr ); However, _beginthreadex does call upon CreateThread(). HANDLE CreateThread( LPSECURITY_ATTRIBUTES secAttr, SIZE_T stackSize, LPTHREAD_START_ROUTINE threadFunc, LPVOID param, DWORD flags, LPDWORD threadID ); However, does anyone have a wrapper or a URL to a library that is compatible with Cygwin/WinGW. Or can offer some advice? As this is the last little piece of moving from VSutdio Project over to makefiles for Windows/Darwin/Linux. Thanks.

    Read the article

  • Conversion from Iphone Core Surface RGB Frame into ffmepg AVFarme

    - by Sridhar
    Hello, I am trying to convert Core Surface RGB frame buffer(Iphone) to ffmpeg Avfarme to encode into a movie file. But I am not getting the correct video output (video showing colors dazzling not the correct picture) I guess there is something wrong with converting from core surface frame buffer into AVFrame. Here is my code : Surface *surface = [[Surface alloc]initWithCoreSurfaceBuffer:coreSurfaceBuffer]; [surface lock]; unsigned int height = surface.height; unsigned int width = surface.width; unsigned int alignmentedBytesPerRow = (width * 4); if (!readblePixels) { readblePixels = CGBitmapAllocateData(alignmentedBytesPerRow * height); NSLog(@"alloced readablepixels"); } unsigned int bytesPerRow = surface.bytesPerRow; void *pixels = surface.baseAddress; for (unsigned int j = 0; j < height; j++) { memcpy(readblePixels + alignmentedBytesPerRow * j, pixels + bytesPerRow * j, bytesPerRow); } pFrameRGB->data[0] = readblePixels; // I guess here is what I am doing wrong. pFrameRGB->data[1] = NULL; pFrameRGB->data[2] = NULL; pFrameRGB->data[3] = NULL; pFrameRGB->linesize[0] = pCodecCtx->width; pFrameRGB->linesize[1] = 0; pFrameRGB->linesize[2] = 0; pFrameRGB->linesize[3] = 0; sws_scale (img_convert_ctx, pFrameRGB->data, pFrameRGB->linesize, 0, pCodecCtx->height, pFrameYUV->data, pFrameYUV->linesize); Please help me out. Thanks, Raghu

    Read the article

  • Vector is pointing to uninitialized bytes when used in recvfrom call

    - by Adam A.
    In a function that I am writing I am trying to return a pointer to a vector of unsigned chars. The relevant code is below. std::vector<unsigned char> *ret = new std::vector<unsigned char>(buffSize,'0'); int n = recvfrom(fd_, &((*ret)[0]) ,buffSize, &recvAddress, &sockSize); //This should work too... recvfrom(fd_, ret ,buffSize, &recvAddress, &sockSize); // display chars somehow just for testing for(std::vector<unsigned char>::iterator it=ret->begin(); it<it->end();i++) { std::cout<<*it; } std::cout<<std::endl; ... return ret; When I run this through valgrind I get errors talking about how the buffer in recvfrom is pointing to uninitialized bytes. I've narrowed this down to the vector since I swapped it out for an unsigned char array and everything works fine. Any suggestions?

    Read the article

  • SIMPLE OpenSSL RSA Encryption in C/C++ is causing me headaches

    - by Josh
    Hey guys, I'm having some trouble figuring out how to do this. Basically I just want a client and server to be able to send each other encrypted messages. This is going to be incredibly insecure because I'm trying to figure this all out so I might as well start at the ground floor. So far I've got all the keys working but encryption/decryption is giving me hell. I'll start by saying I am using C++ but most of these functions require C strings so whatever I'm doing may be causing problems. Note that on the client side I receive the following error in regards to decryption. error:04065072:rsa routines:RSA_EAY_PRIVATE_DECRYPT:padding check failed I don't really understand how padding works so I don't know how to fix it. Anywho here are the relevant variables on each side followed by the code. Client: RSA *myKey; // Loaded with private key // The below will hold the decrypted message unsigned char* decrypted = (unsigned char*) malloc(RSA_size(myKey)); /* The below holds the encrypted string received over the network. Originally held in a C-string but C strings never work for me and scare me so I put it in a C++ string */ string encrypted; // The reinterpret_cast line was to get rid of an error message. // Maybe the cause of one of my problems? if(RSA_private_decrypt(sizeof(encrypted.c_str()), reinterpret_cast<const unsigned char*>(encrypted.c_str()), decrypted, myKey, RSA_PKCS1_OAEP_PADDING)==-1) { cout << "Private decryption failed" << endl; ERR_error_string(ERR_peek_last_error(), errBuf); printf("Error: %s\n", errBuf); free(decrypted); exit(1); } Server: RSA *pkey; // Holds the client's public key string key; // Holds a session key I want to encrypt and send //The below will hold the encrypted message unsigned char *encrypted = (unsigned char*)malloc(RSA_size(pkey)); // The reinterpret_cast line was to get rid of an error message. // Maybe the cause of one of my problems? if(RSA_public_encrypt(sizeof(key.c_str()), reinterpret_cast<const unsigned char*>(key.c_str()), encrypted, pkey, RSA_PKCS1_OAEP_PADDING)==-1) { cout << "Public encryption failed" << endl; ERR_error_string(ERR_peek_last_error(), errBuf); printf("Error: %s\n", errBuf); free(encrypted); exit(1); } Let me once again state, in case I didn't before, that I know my code sucks but I'm just trying to establish a framework for understanding this. I'm sorry if this offends you veteran coders. Thanks in advance for any help you guys can provide!

    Read the article

  • Is it fair for us to conclude XOR string encryption is less secure than well known encryption (Say Blowfish)

    - by Yan Cheng CHEOK
    I was wondering, is it fair to conclude, XOR string encryption is less secure than other encryption method, say Blowfish This is because for both methods, their input are Unencrypted string A secret key string XOR(string value,string key) { string retval(value); short unsigned int klen=key.length(); short unsigned int vlen=value.length(); short unsigned int k=0; short unsigned int v=0; for(v;v<vlen;v++) { retval[v]=value[v]^key[k]; k=(++k<klen?k:0); } return retval; } Is there any proof that XOR encryption method is more easy to be "broken" than Blowfish if the same key is being chosen?

    Read the article

  • 32bit to 64bit inline assembly porting

    - by Simone Margaritelli
    I have a piece of C++ code (compiled with g++ under a GNU/Linux environment) that load a function pointer (how it does that doesn't matter), pushes some arguments onto the stack with some inline assembly and then calls that function, the code is like : unsigned long stack[] = { 1, 23, 33, 43 }; /* save all the registers and the stack pointer */ unsigned long esp; asm __volatile__ ( "pusha" ); asm __volatile__ ( "mov %%esp, %0" :"=m" (esp)); for( i = 0; i < sizeof(stack); i++ ){ unsigned long val = stack[i]; asm __volatile__ ( "push %0" :: "m"(val) ); } unsigned long ret = function_pointer(); /* restore registers and stack pointer */ asm __volatile__ ( "mov %0, %%esp" :: "m" (esp) ); asm __volatile__ ( "popa" ); I'd like to add some sort of #ifdef _LP64 // 64bit inline assembly #else // 32bit version as above example #endif But i don't know inline assembly for 64bit machines, anyone could help me? Thanks

    Read the article

  • My VARCHAR(MAX) field is capping itself at 4000; what gives?

    - by eidylon
    Hello all... I have a table in one of my databases which is a queue of emails. Emails to certain addresses get accumulated into one email, which is done by a sproc. In the sproc, I have a table variable which I use to build the accumulated bodies of the emails, and then loop through to send each email. In my table var I have my body column defined as VARCHAR(MAX), seeing as there could be any number of emails currently accumulated for a given email address. It seems though that even though my column is defined as VARCHAR(MAX) it is behaving as if it were VARCHAR(4000) and is truncating the data going into it, although it does NOT throw any exceptions, it just silently stops concatenating any more data after 4000 characters. The MERGE statement is where it is building the accumulated email body into @EMAILS.BODY, which is the field that is truncating itself at 4000 characters. Below is the code of my sproc... ALTER PROCEDURE [system].[SendAccumulatedEmails] AS BEGIN SET NOCOUNT ON; DECLARE @SENTS BIGINT = 0; DECLARE @ROWS TABLE ( ROWID ROWID, DATED DATETIME, ADDRESS NAME, SUBJECT VARCHAR(1000), BODY VARCHAR(MAX) ) INSERT INTO @ROWS SELECT ROWID, DATED, ADDRESS, SUBJECT, BODY FROM system.EMAILQUEUE WHERE ACCUMULATE = 1 AND SENT IS NULL ORDER BY ADDRESS, DATED DECLARE @EMAILS TABLE ( ADDRESS NAME, ALLIDS VARCHAR(1000), BODY VARCHAR(MAX) ) DECLARE @PRVRID ROWID = NULL, @CURRID ROWID = NULL SELECT @CURRID = MIN(ROWID) FROM @ROWS WHILE @CURRID IS NOT NULL BEGIN MERGE @EMAILS AS DST USING (SELECT * FROM @ROWS WHERE ROWID = @CURRID) AS SRC ON SRC.ADDRESS = DST.ADDRESS WHEN MATCHED THEN UPDATE SET DST.ALLIDS = DST.ALLIDS + ', ' + CONVERT(VARCHAR,ROWID), DST.BODY = DST.BODY + '<i>'+CONVERT(VARCHAR,SRC.DATED,101)+' ' +CONVERT(VARCHAR,SRC.DATED,8) +':</i> <b>'+SRC.SUBJECT+'</b>'+CHAR(13)+SRC.BODY +' (Message ID '+CONVERT(VARCHAR,SRC.ROWID)+')' +CHAR(13)+CHAR(13) WHEN NOT MATCHED BY TARGET THEN INSERT (ADDRESS, ALLIDS, BODY) VALUES ( SRC.ADDRESS, CONVERT(VARCHAR,ROWID), '<i>'+CONVERT(VARCHAR,SRC.DATED,101)+' ' +CONVERT(VARCHAR,SRC.DATED,8)+':</i> <b>' +SRC.SUBJECT+'</b>'+CHAR(13)+SRC.BODY +' (Message ID '+CONVERT(VARCHAR,SRC.ROWID)+')' +CHAR(13)+CHAR(13)); SELECT @PRVRID = @CURRID, @CURRID = NULL SELECT @CURRID = MIN(ROWID) FROM @ROWS WHERE ROWID > @PRVRID END DECLARE @MAILFROM VARCHAR(100) = system.getOption('MAILFROM'), DECLARE @SMTPHST VARCHAR(100) = system.getOption('SMTPSERVER'), DECLARE @SMTPUSR VARCHAR(100) = system.getOption('SMTPUSER'), DECLARE @SMTPPWD VARCHAR(100) = system.getOption('SMTPPASS') DECLARE @ADDRESS NAME, @BODY VARCHAR(MAX), @ADDL VARCHAR(MAX) DECLARE @SUBJECT VARCHAR(1000) = 'Accumulated Emails from LIJSL' DECLARE @PRVID NAME = NULL, @CURID NAME = NULL SELECT @CURID = MIN(ADDRESS) FROM @EMAILS WHILE @CURID IS NOT NULL BEGIN SELECT @ADDRESS = ADDRESS, @BODY = BODY FROM @EMAILS WHERE ADDRESS = @CURID SELECT @BODY = @BODY + 'This is an automated message sent from an unmonitored mailbox.'+CHAR(13)+'Do not reply to this message; your message will not be read.' SELECT @BODY = '<style type="text/css"> * {font-family: Tahoma, Arial, Verdana;} p {margin-top: 10px; padding-top: 10px; border-top: single 1px dimgray;} p:first-child {margin-top: 10px; padding-top: 0px; border-top: none 0px transparent;} </style>' + @BODY exec system.LogIt @SUBJECT, @BODY BEGIN TRY exec system.SendMail @SMTPHST, @SMTPUSR, @SMTPPWD, @MAILFROM, @ADDRESS, NULL, NULL, @SUBJECT, @BODY, 1 END TRY BEGIN CATCH DECLARE @EMSG NVARCHAR(2048) = 'system.EMAILQUEUE.AI:'+ERROR_MESSAGE() SELECT @ADDL = 'TO:'+@ADDRESS+CHAR(13)+'SUBJECT:'+@SUBJECT+CHAR(13)+'BODY:'+@BODY exec system.LogIt @EMSG,@ADDL END CATCH SELECT @PRVID = @CURID, @CURID = NULL SELECT @CURID = MIN(ADDRESS) FROM @EMAILS WHERE ADDRESS > @PRVID END UPDATE system.EMAILQUEUE SET SENT = getdate() FROM system.EMAILQUEUE E, @ROWS R WHERE E.ROWID = R.ROWID END

    Read the article

  • Python TEA implementation

    - by Gaks
    Anybody knows proper python implementation of TEA (Tiny Encryption Algorithm)? I tried the one I've found here: http://sysadminco.com/code/python-tea/ - but it does not seem to work properly. It returns different results than other implementations in C or Java. I guess it's caused by completely different data types in python (or no data types in fact). Here's the code and an example: def encipher(v, k): y=v[0];z=v[1];sum=0;delta=0x9E3779B9;n=32 w=[0,0] while(n>0): y += (z << 4 ^ z >> 5) + z ^ sum + k[sum & 3] y &= 4294967295L # maxsize of 32-bit integer sum += delta z += (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3] z &= 4294967295L n -= 1 w[0]=y; w[1]=z return w def decipher(v, k): y=v[0] z=v[1] sum=0xC6EF3720 delta=0x9E3779B9 n=32 w=[0,0] # sum = delta<<5, in general sum = delta * n while(n>0): z -= (y << 4 ^ y >> 5) + y ^ sum + k[sum>>11 & 3] z &= 4294967295L sum -= delta y -= (z << 4 ^ z >> 5) + z ^ sum + k[sum&3] y &= 4294967295L n -= 1 w[0]=y; w[1]=z return w Python example: >>> import tea >>> key = [0xbe168aa1, 0x16c498a3, 0x5e87b018, 0x56de7805] >>> v = [0xe15034c8, 0x260fd6d5] >>> res = tea.encipher(v, key) >>> "%X %X" % (res[0], res[1]) **'70D16811 F935148F'** C example: #include <unistd.h> #include <stdio.h> void encipher(unsigned long *const v,unsigned long *const w, const unsigned long *const k) { register unsigned long y=v[0],z=v[1],sum=0,delta=0x9E3779B9, a=k[0],b=k[1],c=k[2],d=k[3],n=32; while(n-->0) { sum += delta; y += (z << 4)+a ^ z+sum ^ (z >> 5)+b; z += (y << 4)+c ^ y+sum ^ (y >> 5)+d; } w[0]=y; w[1]=z; } int main() { unsigned long v[] = {0xe15034c8, 0x260fd6d5}; unsigned long key[] = {0xbe168aa1, 0x16c498a3, 0x5e87b018, 0x56de7805}; unsigned long res[2]; encipher(v, res, key); printf("%X %X\n", res[0], res[1]); return 0; } $ ./tea **D6942D68 6F87870D** Please note, that both examples were run with the same input data (v and key), but results were different. I'm pretty sure C implementation is correct - it comes from a site referenced by wikipedia (I couldn't post a link to it because I don't have enough reputation points yet - some antispam thing)

    Read the article

< Previous Page | 37 38 39 40 41 42 43 44 45 46 47 48  | Next Page >