Как конвертировать guid в int
Как конвертировать guid в int
����, � SQL:
declare @a uniqueidentifier
set @a = ’40bf67bb-742c-4355-abb9-dff6a60bd701′
print cast(@a as varbinary)
’40bf67bb-742c-4355-abb9-dff6a60bd701′ => 0xBB67 BF40 2C74 5543 ABB9 DFF6 A60B D701
DCBA-DC-ED-FG-KLMNOP
���� ����� ToByteArray(:
22345200-abe8-4f60-90c8-0d43 c5f6 c0f6 => 0xF6C0 F6C5 430D C890 4F60 ABE8 2234 5200
PO NM LK GF DE CD AB
� ��� ���������.
| |
Naf Member ������: ������ | Fixin, |
16 ��� 08, 10:44����[6575416] �������� | ���������� �������� ���������� |
| |
Naf Member ������: ������ | Fixin, |
16 ��� 08, 10:54����[6575482] �������� | ���������� �������� ���������� |
| |
Fixin Member ������: | ���� ������ ���������� �� �������, � ������� ��������. �� ���� ��������� � �������� ���� � ����� ��� ���. ��������� ������� ��������� |
17 ��� 08, 13:11����[6582788] �������� | ���������� �������� ���������� |
| |
Fixin Member ������: | � ���� �� �� ������ ���������� ��� ����� � ����� ����� ���������������, � ��� �� ���� ���������, ����� ������� ������. |
17 ��� 08, 13:13����[6582801] �������� | ���������� �������� ���������� |
| |
Naf Member ������: ������ | � ��� ����� ���������? � ���� ����������� � ��� ������� ��������������. �������� ����� ���� ������, �� ����� «����������»? � ���������, Naf |
17 ��� 08, 13:16����[6582830] �������� | ���������� �������� ���������� |
| |||
Fixin Member ������: |
’40bf67bb-742c-4355-abb9-dff6a60bd701′.ToByteArray()= ‘22345200-abe8-4f60-90c8-0d43c5f6c0f6’.ToByteArray()= Изменение идентификатора GUID на intНо нигде не могу найти, как это делается? 3 ответаПо умолчанию ASP.NET Identity (с использованием Entity Framework) использует строки в качестве первичных ключей, а не идентификаторы GUID, но сохраняет идентификаторы GUID в этой строке. Вам нужно определить еще несколько классов, я только что создал новый проект (я использую VS2013 Update 2 CTP), вот модели идентификации, которые вам нужно изменить: Вам также нужно будет обновить несколько других мест, просто следите за ошибками компиляции, наиболее частым изменением будет необходимость преобразовать строку, возвращаемую в форму User.Identity.GetUserId () в целое число. Кроме того, отвечая на другой вопрос (я задал этот вопрос), я предоставил пример решения, которое делает именно это, см. репозиторий ниже: Посмотрите этот ответ Хао-кунга в этом сообщение Поэтому, если вам нужны идентификаторы int, вам нужно создать свой собственный класс POCO IUser и реализовать свой IUserStore для своего настраиваемого класса IUser в версии 1.0 RTM. Это то, что у нас не было времени поддерживать, но я прямо сейчас собираюсь сделать это проще (ier) в 1.1. Надеюсь, что скоро что-то будет доступно в ночных сборках. Обновлено с помощью примера 1.1-alpha 1: как получать ночные сборки Если вы обновитесь до последних ночных битов, вы можете попробовать новый API 1.1-alpha1, который должен упростить это сейчас: Вот как, например, должно выглядеть подключение Guids вместо строк Если кто-то обнаружит это при поиске руководства по идентификации 3.0: В файле Startup.cs метод ConfigureServices: И все, не нужно создавать своих менеджеров, как в 2.0 Как перевести ГУИД в число и обратно?И тест соответственно: Тест выдает: Короче, я только не уверен, что мне Злобный Мальчик дал правильный алгол для преобразования ГУИД в число, но если он правильный, то все пучком. Коллеги, на партнерском не могут мне помочь. Может вы подскажете: Переводил ГУИД: «22345200-abe8-4f60-90c8-0d43c5f6c0f6» (39) Вот я и спрашиваю, это: ox90C80D43C5F6C0F64F60ABE822345200 или нет (40) Спецом для тебя запустил скуль и написал: set @a = ’40bf67bb-742c-4355-abb9-dff6a60bd701′ (49) Читаю себе, читаю. Сирожа, все дела. Тут бац, и ссылка на майкрософт. Ну, думаю, вот и гейтсу теперь Осипов снится будет. Потом уже перевел взгляд, увидел автора поста. Вы так не пугайте:) ЗЫ на (23): Вообще, такие вещи сперва стоит проверять. Аутлук хранит строки в UTF-16. Паршивая там экономия будет. Написал функцию конвертации, провел тесты: ГУИД: 40bf67bb-742c-4355-abb9-dff6a60bd701 Что забавно, функции конвертации числа в ГУИД и обратно оказались симметричными, т.е. практически идентичный код, наверное это как раз и говорит о том, что конвертация правильная: Converting GUID to Integer and Backso I have a 3rd party application that I have to interface with, this application needs the userID from my users table. the problem is that I store my userIDs as GUIDs and the 3rd party app only accepts an integer. so I figure, if there is a way to convert a GUID to an integer then be able to convert it back (as i get communications from their server regarding the userID) then I don’t have to recode a too much. any ideas? 6 Answers 6EDIT: you could perhaps store the GUID into a GUIDs table where you assign each a unique integer ID. That way, you could get the GUID back given the integer ID. You’ll need a store a mapping from your Guid to the 3rd party’s integer: either a new «int thirdPartyId» field in your existing user table, or a new table. You would need a 128-bit integer type to hold the equivalent of a GUID. You can use the Guid’s ToByteArray() method to get the bytes and the constructor that accepts a byte array to restore the Guid. You can also you the GetHashCode() method to get an integer, but two different GUIDs may have the same hashcode since there are more possible Guids than 32-bit integers. A Guid much bigger than an integer, and can’t fit in a integer. Add and integer Identity column, that will basically be a second ID column, and give that columnID to the application. Create a new Table (MyUserMappings) With Two Columns 1) ThirdPartyUserID (INT, NOT NULL, IDENTITY(1,1)) 2) MyUserID (GUID, NOTNULL) Insert All GUID FROM your UserID to This table by doing INSERT INTO MyUserMappings(MyUserID) SELECT MyGUIDUserID FROM MyUsers You also need to put a trigger on your MyUsers Table to insert a new row in MyUsersMappings table every time your MyUsers table gets new row. Now Create a View That shows all the fields from your MyUsers Table and ThirdParty UserID Field from your MyUsermappingsTable. Now you will not require any DAL changes to your existing application and your original table is unaffected. So your existing application will stay as it is. And your new code can query the view instead of the table to return the Integer ID and all other user info. Convert Int to GuidI have to convert Convert Int32 into Guids and this is what I came up with. But it’s somehow ugly. Has anybody a better idea? Yes I know the whole thing is ugly but I am a loss of Ideas. The problem is. I am getting data and have to store it into a Table I cannot change. The sending data primary key is a Int and the table primary key I have to store it is a Guid. The problem is I have to understand what object the sender is talking about but can only store it as a Guid. Okay I see I have to provide more info here. I am a Webservice receiving data and have to pass along data to an Interface I also can not control. So I neither can model the data received nor the (Interface)database where I have to send the data. Additionally, I have somehow have to map these two things in a way so I somehow can update an item. sigh 5 Answers 5Here is a simple way to do it: You can change where the copy will happen (vary the index from 0 to 12). It really depends on how you want to define this unusual «int to Guid» conversion. Had the same issues, needed a Int to Guid then back to Int. Old data that used int ID’s but the processing function required a Guid. It was alot less code to write extra functions plus DB changes. Just easier to pass the Int iD in Guid form, knowing that it was not going to use this as its final saving Guid. The save is an Insert, so it was getting a new Guid at the end. Heres’s the code from above and an idea from another post about Guids to ints and getting the Int back out. This Guid2Int should only be passed a Guid that came from an Int. You can take the digits from an int and format them so that they look like a GUID, but that doesn’t make the result a GUID. A GUID is basically a 16 byte number that is computed using an algorithm that guarantees that number is unique. You can generate GUIDs all day long on every computer in the world and not get a duplicate (at least that’s the theory). A reformatted int is not unique and it’s definitely not a GUID. I too needed to encode a primary key (a uint) of a database into a GUID. There is much discussion around whether to use a unit as your Primary key or a Guid, I won’t get into that here, but I used a uint as primary key, with a guid as column and I wanted to encode the primary key into the guid, and get it back from the guid. The below solution encodes a 24bit Primary key (a uint) to a Guid, and decodes it back. It uses DES encryption on the uint. I recognize that the question wanted a 32bit int, this works for 24bit uint, but 32 could be achieved by concatenating two GUIDs, on with the most significant 24bit, and one with the least significant 24 bit to get 48 bits in total. The algorithm is fully tested, and could be used for an int, but is not tested for negative numbers. GUID FormatA GUID format is 32 digits and may be separated by hyphens, and include braces: 00000000-0000-0000-0000-000000000000 (D) which is 8-4-4-12 characters which is 4-2-2-6 bytes as one byte is coded into 2 characters. Other formats of GUIDs exist. The 3 byte uint encrypted to an 8 byte code, which is written into the guid beginning at the 5th byte (which is the 10th character of the Guid ignoring brackets and ‘-‘delimiters). Let ‘z’ represent the coded int, and 0 any other hex character. The resultant coded GUID is It is noted that the GUID may not be globally unique after this. However, given the GUID encodes your primary key, it WILL be unique for your primary key, and will be very difficult to extract the uint from the GUID without the encryption key. as much as DES encryption is secure. ENCRYPTIONThe RemoveChars is copied/adapted from here Removing characters from strings with LINQ WriteBytesToString is as below DECRYPTIONGetBytesFromString. Note that the bytes begin at the 9th index and are 8 bytes long as hard oded in the calling function. See note on the GUID format
|